Sum element values per parents values

时间:2018-03-25 19:22:12

标签: xml xslt

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 个答案:

答案 0 :(得分:0)

以下样式表会迭代每个/root/parent,并计算element/sub-element/elementValue的所有parent元素的总和,lastParent元素包含$#10;个子元素。

它打印总和然后回车(<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> )以将每个值放在一个新行上:

let l = [1..5]
let l1 = [length [ n | n <- l, mod n 2 == 0]]!!0
[l1,(length l) - l1]
-> [2,3]