Question

I am trying to add parent element into XML using XSLT but doesn't get expected result. Please see my XML and XSL code. My transformation add all child under newly added node but I am expecting only DocumentReference under newly added tag.

XML File

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<DataArea>
    <PurchaseOrder>
        <PurchaseOrderLine>
            <DocumentReference>
                    <DocumentID>
                        <ID>23423</ID>
                    </DocumentID>
            </DocumentReference>
            <DocumentReference>
                <DocumentID>
                    <ID>23424</ID>
                </DocumentID>
            </DocumentReference>
            <Item>
                <CustomerItemID>
                    <!-- ArtNr -->
                    <ID>444</ID>
                </CustomerItemID>
            </Item>
            <Quantity unitCode="PCE">17.3</Quantity>
        </PurchaseOrderLine>
    </PurchaseOrder>
</DataArea>

Expected Result

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<DataArea>
     <PurchaseOrder>
          <PurchaseOrderLine>
            <Kiran>
            <DocumentReference>
                <DocumentID>
                     <ID>23423</ID>
                 </DocumentID>
             </DocumentReference>
             <DocumentReference>
                 <DocumentID>
                     <ID>23424</ID>
                 </DocumentID>
              </DocumentReference>
            </Kiran>>
            <Item>
                <CustomerItemID>
                    <!-- ArtNr -->
                    <ID>444</ID>
                </CustomerItemID>
            </Item>
            <Quantity unitCode="PCE">17.3</Quantity>
        </PurchaseOrderLine>
        </PurchaseOrder>
 </DataArea>

XSLT Code

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>

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

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

Solution

You can chooose which elements you want under your parent node by naming them explicitly. This will place only DocumentReference under Kiran.

<xsl:copy>
    <Kiran>
        <xsl:apply-templates select="@*|DocumentReference"/>
    </Kiran>
    <xsl:apply-templates select="@*|Item|Quantity"/>
</xsl:copy>

This is a quick and simple solution, but if you something more generic you can also achieve the same result by other means (ex: using xsl:if, xsl:choose or additional templates) writing a bit more code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top