简体   繁体   English

所有子元素 XML/XSLT 的总和

[英]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.在通过每个父级生成所有值的总和时,我需要 XSLT。 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.父项 1 应返回总和 6,父项 2 应返回总和 4。如您所见,每个父项将具有不同数量的值。 How can I write to simply sum every value under values, regardless of their names?我如何写来简单地总结值下的每个值,而不管它们的名字?

Simply use the sum() function like this:只需像这样使用sum()函数:

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

It creates a <sum> element with the desired value.它创建一个具有所需值的<sum>元素。
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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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