I don’t think well in xsl, so I’m having trouble comprehending how to handle this. I need to make an aggregate of the quantity, but grouped by the id in the attribute in the parent node. I’m thinking this should be a horribly simple recursion template, but I’m having trouble pumping it out
This input xml looks like this:
<foo>
<lines>
<line line_id="10000">
<qty>10</qty>
</line>
<line line_id="10000">
<qty>4</qty>
</line>
<line line_id="10000">
<qty>12</qty>
</line>
<line line_id="20000">
<qty>1</qty>
</line>
<line line_id="30000">
<qty>4</qty>
</line>
<line line_id="30000">
<qty>6</qty>
</line>
</lines>
<lines>
<line line_id="10000">
<qty>4</qty>
</line>
</lines>
</foo>
The output should be:
<newfoo>
<items>
<item>
<item_id>10000</item_id>
<quantity>26</quantity>
</item>
<item>
<item_id>20000</item_id>
<quantity>1</quantity>
</item>
<item>
<item_id>30000</item_id>
<quantity>10</quantity>
</item>
</items>
<items>
<item>
<item_id>10000</item_id>
<quantity>4</quantity>
</item>
</items>
</newfoo>
This can be achieved in XSLT1.0 by using a method called Muenchian Grouping.
Firstly, you define a key to look-up the line elements for a given lines element using the line_id attribute as the key. So, for a given lines element and line_id attribute, all matching line elements will be returned. You will need a concatenated key for this.
Next, you need to match the line elements which have the first occurrence of each distinct line_id attribute within the lines element. This is achieved as follows:
i.e. Match line elements which happen to be the first elements in the list for the given key.
Then, you can get the total quantity, simply by summing all elements in the key
Here is the full XSLT document:
When applied to the following XML:
The following XML is output: