2017-09-25 41 views
0

在XSLT 1.0/XPATH 1.0中,如果不使用任何外部库/节点集扩展,我需要能够将项目的成本值(用于该人的份额)特定项目的类型。例如,在下面的示例XML中,我将如何对'Box'类型和'Andrew'类型的成本进行求和?预期的输出是'1500'(0.5 * 1000 + 1 * 1000)。总结从for-each循环返回的xpaths的值

`<items> 
    <item> 
     <type>Box</type> 
     <cost>1000.00</cost> 
     <share> 
      <person> 
       <name>Jim</name> 
       <percent>50</percent> 
      </person> 
      <person> 
       <name>Andrew</name> 
       <percent>50</percent> 
      </person> 
     </share> 
    </item> 
    <item> 
     <type>Box</type> 
     <cost>1000.00</cost> 
     <share> 
      <person> 
       <name>Andrew</name> 
       <percent>100</percent> 
      </person> 
     </share> 
    </item> 
    <item> 
     <type>Car</type> 
     <cost>2000.00</cost> 
     <share> 
      <person> 
       <name>Andrew</name> 
       <percent>100</percent> 
      </person> 
     </share> 
    </item> 
    <item> 
     <type>Box</type> 
     <cost>2000.00</cost> 
     <share> 
      <person> 
       <name>Jim</name> 
       <percent>100</percent> 
      </person> 
     </share> 
    </item> 
</items>` 

在XSLT,我能有一个for-each循环:

`<xsl:for-each select="/items/item[type='Box' and share/person/name='Andrew']"> 
    <xsl:value-of select="share/person[name='Andrew']/percent div 100) * cost"/> 
</xsl:for-each>` 

但这不会求和汇总。我不认为sum()可以被使用,因为它需要将每个特定项目的数量乘以该人的份额。由于XSLT的限制,我不知道如何将它存储在一个变量中,其中包含for-each循环。我认为递归可能会被使用,但我不知道如何。

+0

您可以编辑您的问题,以显示你的期望是什么输出看起来像请?你真的只是对一个特定的人/类型感兴趣,或者你真的想要显示所有可能的项目和类型的总数?谢谢 –

回答

0

其中XSL extensions,你可以这样做:

 <!-- first, store all the computed values to be summed up in a variable --> 
    <xsl:variable name="vals"> 
     <xsl:for-each select="/items/item[type/text() ='Box' and share/person/name/text() = 'Andrew']"> 
       <val><xsl:value-of select="(cost * share/person[name/text() = 'Andrew']/percent) div 100"/></val> 
      </xsl:for-each> 
    </xsl:variable> 

    <!-- Get the sum of all the values --> 
    <xsl:value-of select="sum(exsl:node-set($vals)/*)" /> 

您还需要添加以下声明样式表的根元素:xmlns:exsl="http://exslt.org/common" extension-element-prefixes="exsl"