VextoR
VextoR

Reputation: 5175

Add one element to the parent element with xslt without copying

I want to add an element to source xml.

Example: Source

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

I want to add element

<LineNumber>10</LineNumber>

to

DataArea/PurchaseOrder/PurchaseOrderLine/

So first solution will be copying all data from original xml and then LineNumber like

<xsl:copy>
    <xsl:apply-templates select="DocumentReference"/>
    <xsl:apply-templates select="Item"/>
    <xsl:apply-templates select="Quantity"/>
        <!-- ADD HERE LINENUMBER -->
</xsl:copy>

How can I add LineNumber without manually copying all elements?

Upvotes: 0

Views: 1946

Answers (1)

Tim C
Tim C

Reputation: 70648

This is straight-forward, just by adding an extra matching template to the standard XSLT Identity Transform

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

This just copies the element, and all its children, but adds the new LineNumber element too.

Here is the full XSLT

<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>
         <xsl:apply-templates select="@*|node()"/>
         <LineNumber>10</LineNumber>
      </xsl:copy>
   </xsl:template>

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

When applied to your XML, the following is output

<DataArea>
   <PurchaseOrder>
      <PurchaseOrderLine>
         <DocumentReference type="customersReference1">
            <DocumentID>
               <ID>23423</ID>
            </DocumentID>
         </DocumentReference>
         <Item>
            <CustomerItemID><!-- ArtNr -->
               <ID>444</ID>
            </CustomerItemID>
         </Item>
         <Quantity unitCode="PCE">17.3</Quantity>
         <LineNumber>10</LineNumber>
      </PurchaseOrderLine>
   </PurchaseOrder>
</DataArea>

Upvotes: 2

Related Questions