XML 递归添加超出父节点

XML Recursive Adding beyond parent node

我正在尝试编写 XSL (1.0) 以递归地从节点添加值。我用谷歌搜索了一下,似乎只要节点是 parent/child 就可以添加功能。我的节点远不止于此。例如,我有:

<Document>
  <Finance>
    <Account>
      <Type>Expense</Expense>
      <Amount>25</Amount>
    </Account>
  </Finance
</Document>
<Document>
  <Finance>
    <Account>
      <Type>Capital</Type>
      <Amount>75</Amount>
    </Account>
  </Finance
</Document>
<Document>
  <Finance>
    <Account>
      <Type>Expense</Type>
      <Amount>50</Amount>
    </Account>
  </Finance
</Document>

我需要通过将所有这些金额相加得到一个变量或总计为 150 的东西。 笔记。这不是确切的结构,但我简化了它。每个文档的节点都是相同的。 我一直在寻找一种基本的方法: 我=0 然后循环加起来 i=i+1

看来这应该是一件容易的事。

我什至想过也许可以 for-each 并创建一个只有两列的 table 然后用它来加起来,但我找不到办法。所以我正在寻找帐户类型和总 运行 金额: 费用 = 75 资本 = 75

如果类别(费用、资本)是恒定的并且事先已知,您可以简单地依次对每个类别求和。这是一个简单的例子:

XML

<root>
   <Document>
      <Finance>
         <Account>
            <Type>Expense</Type>
            <Amount>25</Amount>
         </Account>
      </Finance>
   </Document>
   <Document>
      <Finance>
         <Account>
            <Type>Capital</Type>
            <Amount>100</Amount>
         </Account>
      </Finance>
   </Document>
   <Document>
      <Finance>
         <Account>
            <Type>Expense</Type>
            <Amount>50</Amount>
         </Account>
      </Finance>
   </Document>
</root>

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" version="1.0" encoding="utf-8" indent="yes"/>

<xsl:key name="tx-by-type" match="Account" use="Type" />

<xsl:template match="/root">
    <table border="1">
        <tr>
            <th>Expense</th>
            <th>Capital</th>
            <th>Total</th>
        </tr>
        <tr>
            <xsl:variable name="total-expense" select="sum(key('tx-by-type', 'Expense')/Amount)" />
            <xsl:variable name="total-capital" select="sum(key('tx-by-type', 'Capital')/Amount)" />
            <td>
                <xsl:value-of select="$total-expense" />
            </td>
            <td>
                <xsl:value-of select="$total-capital" />
            </td>
            <td>
                <xsl:value-of select="$total-expense + $total-capital" />
            </td>
        </tr>
    </table>
</xsl:template>

</xsl:stylesheet>

结果

<table border="1">
   <tr>
      <th>Expense</th>
      <th>Capital</th>
      <th>Total</th>
   </tr>
   <tr>
      <td>75</td>
      <td>100</td>
      <td>175</td>
   </tr>
</table>