XSLT aggregating XML tag values and storing new ta

2019-03-07 06:43发布

I'm new to xslt and trying to process below XML using XSLT :

<xml>
<characters>
<char a="a1" b="b1" y="y1" z="z1"  weight="100">F</char>
<char a="a2" b="b2" y="y2" z="z2"  weight="80">r</char>
<char a="a3" b="b3" y="y3" z="z3"  weight="80">o</char>
<char a="a4" b="b4" y="y4" z="z4"  weight="100">m</char>
</characters>
</xml>

to produce output XML :

<word>
<value>From</value>
<coordinates>a1 b1 y4 z4</coordinates>
<avgWeight>90</avgWeight>
</word>

where coordinates form the first and last characters coordinates and avgWeight aggregate the values of weight tag.

Since XSLT variables are immutable, I'm unable perform below operation. Help me in finding solution.

标签: xml xslt
1条回答
不美不萌又怎样
2楼-- · 2019-03-07 07:01

Since XSLT variables are immutable, I'm unable perform below operation.

I don't see what variables, immutable or not, have to do with it. This is just straightforward XSLT:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>

<xsl:template match="/xml">
    <xsl:for-each select="characters">
        <word>
            <value>
                <xsl:for-each select="char">
                    <xsl:value-of select="."/>
                </xsl:for-each>
            </value>
            <coordinates>
                <xsl:value-of select="char[1]/@a"/>
                <xsl:text> </xsl:text>
                <xsl:value-of select="char[1]/@b"/>
                <xsl:text> </xsl:text>
                <xsl:value-of select="char[last()]/@y"/>
                <xsl:text> </xsl:text>
                <xsl:value-of select="char[last()]/@z"/>
            </coordinates>
            <avgWeight>
                <xsl:value-of select="sum(characters/char/@weight) div count(characters/char) "/>
            </avgWeight>
        </word>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>
查看更多
登录 后发表回答