问题
I have the following XML document:
<nodes>
<node>
<type>A</type>
<val>1,000</val>
</node>
<node>
<type>B</type>
<val>2,000</val>
</node>
<node>
<type>A</type>
<val>3,000</val>
</node>
</nodes>
My goal is to get a list of unique types and sum all their <val>
s. I'm getting the following output:
<nodes>
<node>
<type>A</type>
<sum>3</sum>
</node>
<node>
<type>B</type>
<sum>2</sum>
</node>
</nodes>
I was expecting a sum (for type A) of 4000, but I'm getting 3 instead.
Here's my xslt:
<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:key name="type" match="/nodes/node/type/text()" use="." />
<xsl:template match="/">
<nodes>
<xsl:for-each select="/nodes/node/type/text()[generate-id()=generate-id(key('type',.)[1])]">
<node>
<xsl:variable name="t" select="."/>
<type><xsl:value-of select="$t"/></type>
<sum>
<xsl:value-of select="sum(/nodes/node[type=$t]/val)"/>
</sum>
</node>
</xsl:for-each>
</nodes>
</xsl:template>
</xsl:stylesheet>
Any ideas on how I can sum values with commas in them using sum()?
回答1:
This transformation:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ext="http://exslt.org/common" exclude-result-prefixes="ext">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:key name="kType" match="type" use="."/>
<xsl:variable name="vrtfPass1">
<xsl:apply-templates select="/*"/>
</xsl:variable>
<xsl:variable name="vPass1" select="ext:node-set($vrtfPass1)"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/">
<xsl:apply-templates mode="pass2" select=
"$vPass1/*/*/type[generate-id()=generate-id(key('kType',.)[1])]"/>
</xsl:template>
<xsl:template match="val/text()[true()]">
<xsl:value-of select="translate(., translate(.,'01234567890', ''), '')"/>
</xsl:template>
<xsl:template match="type" mode="pass2">
<type><xsl:value-of select="."/></type>
<sum><xsl:value-of select="sum(key('kType',.)/../val)"/></sum>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document:
<nodes>
<node>
<type>A</type>
<val>1,000</val>
</node>
<node>
<type>B</type>
<val>2,000</val>
</node>
<node>
<type>A</type>
<val>3,000</val>
</node>
</nodes>
produces the wanted, correct result:
<type>A</type>
<sum>4000</sum>
<type>B</type>
<sum>2000</sum>
来源:https://stackoverflow.com/questions/15056913/how-to-sum-values-with-commas-using-sum