Sum element values per parents values

2019-09-01 03:44发布

问题:

For each value of the node parent, I want to sum the related element values. In the below example, I am expecting to have 3 results : 30 for the first parent, 50 for the second and 0 for the 3rd parent as it has no parent value. can you help me getting this result please and rectify my code ? :

Example file :

<root>
    <parent>
        <sub-parent>
            <lastparent>
                <parentValue>Val1</parentValue>
            </lastparent>
        </sub-parent>
        <element>
            <sub-element>
                <elementname>A</elementname>
                <elementvalue>10</elementvalue>
            </sub-element>
        </element>
        <element>
            <sub-element>
                <elementname>A</elementname>
                <elementvalue>20</elementvalue>
            </sub-element>
        </element>
    </parent>
    <parent>
        <sub-parent>
            <lastparent>
                <parentValue>Val2</parentValue>
            </lastparent>
        </sub-parent>
        <element>
            <sub-element>
                <elementname>B</elementname>
                <elementvalue>50</elementvalue>
            </sub-element>
        </element>
    </parent>
    <parent>
        <element>
            <sub-element>
                <elementname>C</elementname>
                <elementvalue>60</elementvalue>
            </sub-element>
        </element>
    </parent>
</root>

Code :

<xsl:template match="/">
    <xsl:for-each select="/root/parent/sub-parent/lastparent">
      <xsl:variable name="result">
        <xsl:value-of select="sum(element/sub-element/elementvalue)" />
      </xsl:variable>
    </xsl:for-each>
</xsl:template>

回答1:

The following stylesheet iterates over each /root/parent and calculates the sum of the element/sub-element/elementValue that are following-siblings of parent elements that have lastParent children.

It prints the sum and then a carriage-return ($#10;) to put each value on a new line:

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

  <xsl:output method="html" encoding="utf-8" indent="yes" />

  <xsl:template match="/">
    <xsl:for-each select="/root/parent">
      <xsl:variable name="result">
        <xsl:value-of select="sum(sub-parent[lastparent]/following-sibling::element/sub-element/elementvalue)" />
      </xsl:variable>
      <xsl:value-of select="concat($result,'&#10;')"/>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>


标签: xml xslt