Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding element in middle of xml using xslt

Tags:

xslt

Below is the actual xml:

<?xml version="1.0" encoding="utf-8"?> <employee>  <Name>ABC</Name>  <Dept>CS</Dept>  <Designation>sse</Designation> </employee> 

And i want the output as below:

<?xml version="1.0" encoding="utf-8"?> <employee>  <Name>ABC</Name>   <Age>34</Age>  <Dept>CS</Dept>   <Domain>Insurance</Domain>  <Designation>sse</Designation> </employee> 

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

like image 888
Madhu CM Avatar asked Sep 06 '10 05:09

Madhu CM


People also ask

How do I create a new element in XSLT?

name (mandatory): Name of the element you want to create. Set to an attribute value template that returns a QName. namespace (optional): The namespace uniform resource identifier (URI) of the new element. Set to an attribute value template returning a URI.

What is number () in XSLT?

Definition and Usage. The <xsl:number> element is used to determine the integer position of the current node in the source. It is also used to format a number.

What is text () in XSLT?

XSLT <xsl:text> The <xsl:text> element is used to write literal text to the output. Tip: This element may contain literal text, entity references, and #PCDATA.

What is current group () in XSLT?

Returns the contents of the current group selected by xsl:for-each-group. Available in XSLT 2.0 and later versions. Available in all Saxon editions. current-group() ➔ item()*


1 Answers

Here is an XSLT 1.0 stylesheet that will do what you asked:

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">    <!-- Identity transform -->    <xsl:template match="@* | node()">       <xsl:copy>          <xsl:apply-templates select="@* | node()"/>       </xsl:copy>    </xsl:template>     <xsl:template match="Name">       <xsl:copy-of select="."/>       <Age>34</Age>    </xsl:template>     <xsl:template match="Dept">       <xsl:copy-of select="."/>       <Domain>Insurance</Domain>    </xsl:template> </xsl:stylesheet> 

Obviously the logic will vary depending on where you will be getting the new data from, and where it needs to go. The above stylesheet merely inserts an <Age> element after every <Name> element, and a <Domain> element after every <Dept> element.

(Limitation: if your document could have <Name> or <Dept> elements within other <Name> or <Dept> elements, only the outermost ones will have this special processing. I don't think you intend for your document to have this kind of recursive structure, so it wouldn't affect you, but it's worth mentioning just in case.)

like image 105
LarsH Avatar answered Oct 05 '22 07:10

LarsH