In the below two ASNInPO’s po_nbr is same container_id under ASNInCtn is same and item_id under ASNInItem is different. In this case two ASNInPO’s has to be merged and two ASNInCtn’s has to be merged into one tag.
This is my Input:
<?xml version = '1.0' encoding = 'UTF-8'?>
<ASNInDesc>
<asn_nbr>ASN-1</asn_nbr>
<ASNInPO>
<po_nbr>PO-2</po_nbr>
<ASNInCtn>
<container_id>CONTAINER-2</container_id>
<ASNInItem>
<item_id>ITEM-2</item_id>
<unit_qty>3</unit_qty>
</ASNInItem>
</ASNInCtn>
</ASNInPO>
<ASNInPO>
<po_nbr>PO-2</po_nbr>
<ASNInCtn>
<container_id>CONTAINER-2</container_id>
<ASNInItem>
<item_id>ITEM-3</item_id>
<unit_qty>3</unit_qty>
</ASNInItem>
</ASNInCtn>
</ASNInPO>
</ASNInDesc>
This is the desired output:
<?xml version = '1.0' encoding = 'UTF-8'?>
<ASNInDesc>
<asn_nbr>ASN-1</asn_nbr>
<ASNInPO>
<po_nbr>PO-2</po_nbr>
<ASNInCtn>
<container_id>CONTAINER-2</container_id>
<ASNInItem>
<item_id>ITEM-2</item_id>
<unit_qty>3</unit_qty>
</ASNInItem>
<ASNInItem>
<item_id>ITEM-3</item_id>
<unit_qty>3</unit_qty>
</ASNInItem>
</ASNInCtn>
</ASNInPO>
</ASNInDesc>
Please help me in solving this.
Since this question is tagged with
xslt-1.0, I’ll post a XSLT1.0 solution using the Muenchian grouping method. (Perhaps someone
else will contribute a XSLT 2.0 solution. It might be instructive to
compare them.)
Let’s walk through the stylesheet.
Grouping 1:
ASNInPOelements bypo_nbrSince we want to group
ASNInPOelements by theirpo_nbr, let’sstart by defining a key which allows retrieving
ASNInPOelements by their
po_nbrvalue.Then we’ll write a template which matches an
ASNInDesc. We’ll make acopy of the element, along with its
asn_nbr. Now we want to groupthe contained
ASNInPOelements by theirpo_nbr. We do this byapplying templates to the first
ASNInPoin each group:Grouping 2:
ASNInCtnelements bycontainer_idBut before we go further, we’ll need to define another key. It seems
like we need to group
ASNInCtnelements by theircontainer_id(see note below if this is not the case).We’ll need that key in the following template which matches
ASNInPOelements. Remember that the elements we process here will be the first
ones of their group, since we selected only those in the
xsl:apply-templateabove.This template is similar to the one we wrote above. We make copy of
the element itself along with its
po_nbrand then again applytemplates to the first
ASNInCtnelements grouped by theircontainer_id:Finally, we write the template which matches
ASNInCtnelements. Thiscopies the element itself, and its
container_idand then copies allASNInItemelements in the same group:And we’re done.
Note
The solution assumes that the
ASNInCtnelement with a givencontainer_idcan only appear withinASNInPOelements with the samepo_nbr. If this is not the case, then you need to adjust the key forASNInPOobjects to use a combination ofpo_nbrandcontainer_id.