user3520080
user3520080

Reputation: 443

Insert new Node inside Node XSLT

I have a XML as seen below. The values are all mocked up just for testing purposes

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<TAG1>

  <placeholder>ghgh</placeholder>

  <placeholder>ghg</placeholder>

  <placeholder>ghgh</placeholder>

  <placeholder>ghg</placeholder>

  <placeholder>ghgh</placeholder>

  <placeholder>ghg</placeholder>

  <Information>

    <InformationBody>

      <Test>EE</Test>

      <TestTwo>QU1RIENUVEIxICAgICAgIBI3f1QK6wEs</TestTwo>

      <TestThree>20150119.141224508</TestThree>

    </InformationBody>

  </Information>

</TAG1>

I need to append a new node after the InformationBody tag with some more extra data how would I go about doing this? I am new to XSLT and have came up with the above but i'm not sure if it's on the right track.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <!-- Identity template, copies everything as is -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <!-- Override for target element -->
  <xsl:template match="TAG1">
    <!-- Copy the element -->
    <xsl:copy>
      <!-- And everything inside it -->
      <xsl:apply-templates select="@* | *"/> 
      <!-- Add new node -->
      <xsl:element name="newNode"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

The final result would look like

<Information>
<InformationBody>

      <Test>EE</Test>

      <TestTwo>QU1RIENUVEIxICAgICAgIBI3f1QK6wEs</TestTwo>

      <TestThree>20150119.141224508</TestThree>

    </InformationBody>

<newTag></newTag>
</Information>

Upvotes: 3

Views: 13880

Answers (1)

Linga Murthy C S
Linga Murthy C S

Reputation: 5432

You can match the InformationBody element, copy it as-is, then add an element after it is copied. As below:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!-- Identity template, copies everything as is -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <!-- Override for target element -->
    <xsl:template match="InformationBody">
        <!-- Copy the element -->
        <xsl:copy>
            <!-- And everything inside it -->
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
        <!-- Add new node -->
        <xsl:element name="newNode"/>
    </xsl:template>
</xsl:stylesheet>

Your approach will work the same if there are no elements after InformationBody. If there are, the newNode will be added after all of the children of TAG1.

Upvotes: 7

Related Questions