Reputation: 57
The sample xml file is shown below
<a>
<apple color="red"/>
</a>
What should I write in XSLT so that i can get the sample output below ?
<AAA>
<BB bbb="#apple"/> <!-- if possible make it auto close -->
</AAA>
Upvotes: 2
Views: 222
Reputation: 56162
Use name()
or local-name()
functions:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/a">
<AAA>
<xsl:apply-templates/>
</AAA>
</xsl:template>
<xsl:template match="*">
<BB bbb="{concat('#', name())}"/>
</xsl:template>
</xsl:stylesheet>
Upvotes: 1
Reputation: 243459
Here is a generic solution, that accept the name replacements to be made as parameters:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:param name="pReps">
<e oldName="a" newName="AAA"/>
<e oldName="apple" newName="BB"/>
<a oldName="color" newName="bbb"/>
</xsl:param>
<xsl:variable name="vReps" select=
"document('')/*/xsl:param[@name='pReps']"/>
<xsl:template match="*">
<xsl:element name=
"{$vReps/e[@oldName = name(current())]/@newName}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name=
"{$vReps/a[@oldName = name(current())]/@newName}">
<xsl:value-of select="concat('#', name(..))"/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied on the provided XML document:
<a>
<apple color="red"/>
</a>
the wanted, correct result is produced:
<AAA>
<BB bbb="#apple"/>
</AAA>
Upvotes: 2