I am trying to modify the XML using <xsl:for-each>
and it is giving me weird results, it's getting overridden all the time.
Version 1.0
Is there any way we can achieve it ?
Input:
<Test>
<Tests>
<Tests1 name="value1" value = "10" />
<Tests1 name="value2" value = "20" />
</Tests>
<Tests>
<Tests1 name="value1" value = "30" />
<Tests1 name="value2" value = "40" />
</Tests>
</Test>
Expected result
<Test value1Sum = "40" value2Sum="60">
</Test>
CodePudding user response:
One way of reporting the sum()
of all the @value
for the various @name
. Using xsl:key
for @name
you can use xsl:for-each
and for each of the distinct names, generate an attribute that appends "Sum" to the name and the sum()
of all the @value
for that @name
selected with key()
and then traversing from @name
to it's @value
via XPath.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:key name="names" match="*[@value]/@name" use="."/>
<xsl:template match="Test">
<Test>
<xsl:for-each select="//@name[generate-id() = generate-id(key('names', .)[1])]">
<xsl:attribute name="{concat(.,'Sum')}">
<xsl:value-of select="sum(key('names', .)/parent::*/@value)"/>
</xsl:attribute>
</xsl:for-each>
</Test>
</xsl:template>
</xsl:stylesheet>