In the below input we have to check the supplier code if it is match to any of the node supplier code then we have to perform sum operation on Quantity.otherwise directly map the quantity.
input:
<Move-Afile>
<Afile>
<Item>
<suppliercode>1</suppliercode>
<PackNumber>1234</PackNumber>
<Quantity>12</Quantity>
</Item>
<Item>
<suppliercode>2</suppliercode>
<PackNumber>567</PackNumber>
<Quantity>3</Quantity>
</Item>
<Item>
<suppliercode>1</suppliercode>
<PackNumber>567</PackNumber>
<Quantity>8</Quantity>
</Item>
<Item>
<suppliercode>3</suppliercode>
<PackNumber>126</PackNumber>
<Quantity>11</Quantity>
</Item>
<Item>
<suppliercode>4</suppliercode>
<PackNumber>876</PackNumber>
<Quantity>32</Quantity>
</Item>
</Afile>
</Move-Afile>
If supplier code is equal then perform sum operation on Quantity,otherwise directly map the Quantity.
output:
<A>
<target>
<Item>
<suppliercode>1</suppliercode>
<PackNumber>1234</PackNumber>
<Quantity>20</Quantity>
</Item>
<Item>
<suppliercode>2</suppliercode>
<PackNumber>567</PackNumber>
<Quantity>3</Quantity>
</Item>
<Item>
<suppliercode>1</suppliercode>
<PackNumber>567</PackNumber>
<Quantity>20</Quantity>
</Item>
<Item>
<suppliercode>3</suppliercode>
<PackNumber>126</PackNumber>
<Quantity>11</Quantity>
</Item>
<Item>
<suppliercode>4</suppliercode>
<PackNumber>876</PackNumber>
<Quantity>32</Quantity>
</Item>
</target>
</A>
i need the sum logic in a separate temporary variable like below.
<varaible name=tempvar>
<xsl:choose>
<xsl:when suppliercode=suppliercode>
<xsl:value-of select=sum(quntity)/>
<xsl:when>
<xsl:otherwise>
<xsl:value-of select=quntity/>
</xsl:otherwise>
</xsl:choose>
</variable>
This short and efficient (using a key) transformation:
when applied on the provided XML document:
produces the wanted, correct result:
Do note:
The time complexity of this transformation is linear (O(N)). This can be orders of magnitude more efficient than repeatedly scanning all elements to find the ones having a given
suppliercode
-- which has quadratical (O(N^2)) time complexity.Update:
The OP has specified a new requirement, that the sum or the single quantity be captured in a variable:
Just modify this:
into this:
This stylesheet does what you require. It copies all elements from
Item
downwards, and has a special template to change the value ofQuantity
by adding the values of allQuantity
elements fromItem
elements that have the same value ofsuppliercode
.output
Update To put the total into a variable before using it, you can replace the last template with this
which sets the value of
$total
to the sum of the quantities with the same suppplier code.