user2949419
user2949419

Reputation: 51

merging same structured xml with total on attribute using xslt

I Hvae two xml of same structure , I just want the sum of attribute in final xml. Like in below input1.xml and input2.xml atribute dataset has value 20 and input2 has value 30 so output.xml should have value=50

input1.xml

<?xml version="1.0" encoding="UTF-8"?>
<chart xmlns=" "
       labelStep="1"
       showValues="0"
       anchorRadius="1"
      >
   <categories>
      <category Label="Technical RATH"/>
      <category Label="Technical RATH2"/>
   </categories>
   <dataset>
      <set value="20" color="a5cf5a"/>
      <set value="10" color="b5cf5a"/>
   </dataset>
</chart>

input2.xml

<?xml version="1.0" encoding="UTF-8"?>
<chart xmlns=" "
       labelStep="1"
       showValues="0"
       anchorRadius="1"
      >
   <categories>
      <category Label="Technical RATH"/>
      <category Label="Technical RATH2"/>
   </categories>
   <dataset>
      <set value="30" color="a5cf5a"/>
      <set value="150" color="b5cf5a"/>
   </dataset>
</chart>

and output.xml should be

<?xml version="1.0" encoding="UTF-8"?>
<chart xmlns=" "
       labelStep="1"
       showValues="0"
       anchorRadius="1"
      >
   <categories>
      <category Label="Technical RATH"/>
      <category Label="Technical RATH2"/>
   </categories>
   <dataset>
      <set value="50" color="a5cf5a"/>
      <set value="160" color="b5cf5a"/>
   </dataset>
</chart>

Upvotes: 1

Views: 112

Answers (1)

smj
smj

Reputation: 1284

You'll need to fix up what is going on with your namespaces in these documents and adapt the below to suit, but leaving that aside, you can do this:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

<xsl:output method="xml" indent="yes"/>

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="set/@value">
    <xsl:attribute name="value">
        <xsl:value-of select="number(.) + number(document('source2.xml')/chart/dataset/set/@value)"/>
    </xsl:attribute>
</xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions