简体   繁体   中英

Sum of all sub-elements XML/XSLT

How would I add all the numerical elements of all the sub elements for each parent?

Example:

<root>
   <parent id="1">
      <values>
         <valuea>1</valuea>
         <valueb>2</valueb>
         <valuec>3</valuec>
      </vlaues>
   </parent>

   <parent id="2">
      <values>
         <valuea>1</valuea>
         <valuec>3</valuec>
      </vlaues>
   </parent> 
</root>

I need the XSLT when going through each parent to produce the sum of all the values. Parent 1 should return a sum of 6, Parent 2 a sum of 4. As you can see, each parent will have a different amount of values. How can I write to simply sum every value under values, regardless of their names?

Simply use the sum() function like this:

<xsl:template match="values">
  <sum><xsl:copy-of select="sum(*)" /></sum>
</xsl:template>

It creates a <sum> element with the desired value.
In a whole stylesheet this could look like the following:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>

  <!-- Identity template -->
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="values">
    <sum><xsl:copy-of select="sum(*)" /></sum>
  </xsl:template>
  
</xsl:stylesheet>

Its output is

<root>
   <parent id="1">
      <sum>6</sum>
   </parent>

   <parent id="2">
      <sum>4</sum>
   </parent> 
</root>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM