user2842773
user2842773

Reputation: 77

Need help transforming xml via xlst

Hi I need to sum element values in xml via xlst 1.0 and give certain output.

This is the xml I'm working on

<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>

and the desired output would be:

<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>

Whatever I did so fare, either gave me 000 as the sum for the elements or output errors. If someone could point me in the right direction I would appreciate it very much. Thank you in advance.

Upvotes: 0

Views: 61

Answers (1)

Isaac G Sivaa
Isaac G Sivaa

Reputation: 1299

Please find the XSLT which helps to achieve you requirement

<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>

Output of the above XSLT:

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

Upvotes: 0

Related Questions