How to rename an xml node using xsl?

I have an xml structure like below.

<Root>
<Books Name=“C++” Author=“Unknown”>
<Book Price=“30”/>
<Book Price=“50”/>
<Book Price=“45”/>
</Books>
</Root>

Using an xsl,I want to rename only the Books node to “TechBooks” and this new node will have all the attributes and child nodes which the oroginal node has.

So the new xml will be :
<Root>
<TechBooks Name=“C++” Author=“Unknown”>
<Book Price=“30”/>
<Book Price=“50”/>
<Book Price=“45”/>
</TechBooks>
</Root>

Can u pls tell me the best possible way to do this in xsl…?

Thanks,

Hi,
This is fairly easily done by creating a new element and copying across the attributes that the old one had, then using a default copy-all template when using xsl:apply-templates to copy everything the Books node contained.

As an example:


<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <!-- Copy all nodes that we dont want to handle specificly -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Root/Books">
        <xsl:element name="TechBooks">
            <xsl:attribute name="Name"><xsl:value-of select="@Name" /></xsl:attribute>
            <xsl:attribute name="Author"><xsl:value-of select="@Author"/></xsl:attribute>

            <xsl:apply-templates />
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

Applying that to the code you specified would give the result:


<?xml version="1.0" encoding="utf-8"?>
<Root>

   <TechBooks Name="C++" Author="Unknown">

      <Book Price="30"/>

      <Book Price="50"/>

      <Book Price="45"/>

   </TechBooks>

</Root>

I hope that helps.

Regards,

  • Harry :slight_smile:

Sorry my mistake…!! I did not mention in my question that the attributes of the node “Books” are not known.
So for this i made the xsl as below:

<?xml version=“1.0” encoding=“UTF-8”?>
<xsl:stylesheet version=“1.0” xmlns:xsl=“http://www.w3.org/1999/XSL/Transform” xmlns:fo=“http://www.w3.org/1999/XSL/Format” xmlns:msxml=“urn:schemas-microsoft-com:xslt”>
<xsl:output method=“xml” omit-xml-declaration=“yes” version=“1.0” encoding=“UTF-8” indent=“yes”/>
<xsl:template match=“/”>
<xsl:variable name=“oldNode” select=“/Root/Books”/>
<xsl:variable name=“newNodeXml”>
<xsl:element name=“TechBooks”>
<xsl:copy-of select=“$oldNode/@“/>
<xsl:copy-of select=”$oldNode/child::
”/>
</xsl:element>
</xsl:variable>
<xsl:copy-of select=“msxml:node-set($newNodeXml)”/>
</xsl:template>
</xsl:stylesheet>

Anyway,thanks for ur quick response…!

Regards,
livehed