需要帮助通过xslt转换xml

时间:2014-06-25 23:02:29

标签: xml xslt

嗨我需要通过xlst 1.0对xml中的元素值求和并给出一定的输出。

这是我正在处理的xml

<store> 
<counter>
    <item>
        <id>1</id>
        <name>Desk</name>
        <price>96</price>
    </item>
    <item>
        <id>1</id>
        <name>Chair</name>
        <price>323</price>
    </item>
    <item>
        <id>1</id>
        <name>Lamp</name>
        <price>52</price>
    </item>
    <item>
        <id>2</id>
        <name>Desk</name>
        <price>200</price>
    </item>
    <item>
        <id>2</id>
        <name>Chair</name>
        <price>62</price>
    </item>
    <item>
        <id>3</id>
        <name>Desk</name>
        <price>540</price>
    </item>
    <item>
        <id>3</id>
        <name>Desk</name>
        <price>235</price>
    </item>
    <item>
        <id>3</id>
        <name>Desk</name>
        <price>455</price>
    </item>
    <item>
        <id>4</id>
        <name>Desk</name>
        <price>370</price>
    </item>
</counter>
</store>

,所需的输出为:

<Name>Desk</Name>
<Sum> "sum of the Desk prices </Sum>

<Name>Chair</Name>
<Sum> "sum of the Chair prices </Sum>

<Name>Lamp</Name>
<Sum> "sum of the Lamp prices </Sum>

无论我做了什么,所以要么给我000作为元素或输出错误的总和。如果有人能指出我正确的方向,我会非常感激。提前谢谢。

1 个答案:

答案 0 :(得分:0)

请找到有助于满足您要求的XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="xml"/>
<xsl:key name="lang" match="item" use="name"/>
<xsl:template match="/">
  <Output>
     <xsl:for-each select="//item[count(. | key('lang', name)[1]) = 1]">
        <Name>
           <xsl:value-of select="name"/>
        </Name>
        <Sum>
           <xsl:value-of select="sum(key('lang', name)//price)"/>
        </Sum>
     </xsl:for-each>
  </Output>
</xsl:template>
</xsl:stylesheet>

上述XSLT的输出:

<Output>
 <Name>Desk</Name>
 <Sum>1896</Sum>
 <Name>Chair</Name>
 <Sum>385</Sum>
 <Name>Lamp</Name>
 <Sum>52</Sum>
</Output>