John
John

Reputation: 105

Adding element in the middle of xml using xslt

Input XML Below:-

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <Change xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <Area>
            <Sender>
                <LogicalId>tyhu</LogicalId>
            </Sender>
            <CreationDateTime>2021-04-29T14:33:13Z</CreationDateTime>
            <Id1>
                <Id>163067354</Id>
            </Id1>
        </Area>
        <Data>
            <Prob>
                <DateTime>2021-04-29T14:33:13Z</DateTime>
            </Prob>
        </Data>
    </Change>

I need to add two elements Id2 and Id3 after Id1.

Desired Output:-

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <Change xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <Area>
            <Sender>
                <LogicalId>tyhu</LogicalId>
            </Sender>
            <CreationDateTime>2022-04-29T14:33:13Z</CreationDateTime>
            <Id1>
                <Id>6654</Id>
            </Id1>
            <Id2>C1</Id2>
            <Id3>29</Id3>
        </Area>
        <Data>
            <Prob>
                <DateTime>2022-04-29T14:33:13Z</DateTime>
            </Prob>
        </Data>
    </Change>

I tried below xslt but no luck:-

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:output indent="yes"/>
        <xsl:mode on-no-match="shallow-copy"/>
        <xsl:template match="Id1">
            <Id2>C1</Id2>
            <Id3>29</Id3>
            <xsl:next-match/>
        </xsl:template>
    </xsl:stylesheet>

Please let me know if it is possible to do through xslt. Appreciate your help!

Upvotes: 0

Views: 93

Answers (1)

zx485
zx485

Reputation: 29022

Simply use this template:

<xsl:template match="Id1">
  <xsl:next-match />
  <Id2>C1</Id2>
  <Id3>29</Id3>
</xsl:template>

To complete the task with XSLT-1.0, you would have to use the identity template and replace the <xsl:next-match /> by <xsl:copy-of select="." />, but with XSLT-3.0, you can use the <xsl:mode on-no-match="shallow-copy"/>, as you did in your example.

The result is:

<?xml version="1.0" encoding="UTF-8"?>
<Change xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <Area>
      <Sender>
         <LogicalId>tyhu</LogicalId>
      </Sender>
      <CreationDateTime>2021-04-29T14:33:13Z</CreationDateTime>
      <Id1>
         <Id>163067354</Id>
      </Id1>
      <Id2>C1</Id2>
      <Id3>29</Id3>
   </Area>
   <Data>
      <Prob>
         <DateTime>2021-04-29T14:33:13Z</DateTime>
      </Prob>
   </Data>
</Change>

Upvotes: 1

Related Questions