25

This is my XML-

<CATALOG>
    <NAME>C1</NAME>
    <CD>
        <NAME>Empire Burlesque</NAME>
        <ARTIST>Bob Dylan</ARTIST>
        <COUNTRY>USA</COUNTRY>
        <COMPANY>Columbia</COMPANY>
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </CD>
    <CD>
        <NAME>Hide your heart</NAME>
        <ARTIST>Bonnie Tyler</ARTIST>
        <COUNTRY>UK</COUNTRY>
        <COMPANY>CBS Records</COMPANY>
        <PRICE>9.90</PRICE>
        <YEAR>1988</YEAR>
    </CD>
</CATALOG>

I want to replace the NAME tag in catalog to CATALOG-NAME and the the NAME tag in CD's to CD-NAME which should make my xml look like this-

<CATALOG>
    <CATALOG-NAME>C1</CATALOG-NAME>
    <CD>
        <CD-NAME>Empire Burlesque</CD-NAME>
        <ARTIST>Bob Dylan</ARTIST>
        <COUNTRY>USA</COUNTRY>
        <COMPANY>Columbia</COMPANY>
        <PRICE>10.90</PRICE>
        <YEAR>1985</YEAR>
    </CD>
    <CD>
        <CD-NAME>Hide your heart</CD-NAME>
        <ARTIST>Bonnie Tyler</ARTIST>
        <COUNTRY>UK</COUNTRY>
        <COMPANY>CBS Records</COMPANY>
        <PRICE>9.90</PRICE>
        <YEAR>1988</YEAR>
    </CD>
</CATALOG>
onzinsky
  • 541
  • 1
  • 6
  • 21
Srinivas
  • 349
  • 2
  • 4
  • 6
  • I have been trying using XSLT and I'm not finding any function which would change the tag vale. The example I posted above is similar to what I need to do with a larger XML file where I would be replacing tags. – Srinivas Aug 30 '11 at 16:45

1 Answers1

48

Use the identity transform with overrides for the elements you want to rename:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="CD/NAME">
        <CD-NAME><xsl:apply-templates select="@*|node()" /></CD-NAME>
    </xsl:template>
    <xsl:template match="CATALOG/NAME">
        <CATALOG-NAME><xsl:apply-templates select="@*|node()" /></CATALOG-NAME>
    </xsl:template>
</xsl:stylesheet>
Wayne
  • 59,728
  • 15
  • 131
  • 126
  • Can you please include a 1 line description of how this code works? Thanks! – Akhoy Nov 08 '17 at 15:01
  • The identity transform produces output identical to its input. In this case, we slightly modify the identity transform to match `CD/NAME` and `CATALOG/NAME` elements and produce the renamed output for those particular tag names. Everything else remains the same. This is a common pattern. – Wayne Nov 10 '17 at 17:20