I'm new to xslt, Please help: i want to create new elements in existing xml file using xslt. Please find the below sample code.
Existing output:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="class.xsl"?>
<class>
<student>Jack</student>
<student>Harry</student>
<student>Rebecca</student>
<teacher>Mr. Bean</teacher>
</class>
Expected output:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="class.xsl"?>
<class>
<student>Jack</student>
<student>Harry</student>
<student>Rebecca</student>
<teacher>Mr. Bean</teacher>
<professor>SaiBaba</professor>
</class>
One of the simplest and shortest template including logic towards your question would be:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="@* | node()" name="identity-copy">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="class">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
<professor>SaiBaba</professor>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
@* matches all attributes
node() is a function to match all elements on child-axes with type
First template named indentity-copy is a 1:1 copy from source to output. See more infos at Wiki here.
The second template matches your element class, copies itself, and adds the element professor. Alternativ way: You can create the elements in a more strict version via XSL commands to reduce/avoid whitespace or namespace problems:
<xsl:element name="professor">
<xsl:text>SaiBaba</xsl:text>
</xsl:element>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With