0

Below is the actual xml:

<?xml version="1.0" encoding="utf-8"?>
<Procedures>
 <Title>ABC</Title>
 <P>CS</P>
 <div><P>sse</P></div>
</Procedures>

And i want the output as below:

 <?xml version="1.0" encoding="utf-8"?>
    <Procedures>
     <Title>ABC</Title>
     <body>
       <P>CS</P>
       <div><P>sse</P></div>
     </body>
    </Procedures>

Is this possible to add XML element in between using xslt? Please give me sample!

Shanto George
  • 994
  • 13
  • 26
  • Does this answer your question? [Converting XML file to another XML file using XSLT](https://stackoverflow.com/questions/6002772/converting-xml-file-to-another-xml-file-using-xslt) – Nazim Aug 18 '20 at 08:00

2 Answers2

2

Assuming Title is the only element that should be outside of the body you could use the following XLST 1.0 stylesheet:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="Procedures">
    <xsl:copy>
      <xsl:apply-templates select="@*|Title"/>
      <body>
        <xsl:apply-templates select="*[not(self::Title)]"/>
      </body>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
gigermocas
  • 191
  • 2
  • 6
1

You could do this with xmlstarlet, e.g.:

xmlstarlet ed -s /Procedures --type elem -n body \
              -m Procedures/P   Procedures/body  \
              -m Procedures/div Procedures/body  \
              infile.xml

That is, add a subnode body, move P and div to that subnode. Output:

<Procedures>
  <Title>ABC</Title>
  <body>
    <P>CS</P>
    <div>
      <P>sse</P>
    </div>
  </body>
</Procedures>
Thor
  • 45,082
  • 11
  • 119
  • 130