Use name() function to get attribute name
File: Data.xml
<?xml version="1.0" encoding="utf-8"?>
<cars>
<manufacturer name="Chevrolet">
<car>Cavalier</car>
<car>Corvette</car>
<car>Impala</car>
<car>Malibu</car>
</manufacturer>
<manufacturer name="Ford">
<car>Pinto</car>
<car>Mustang</car>
<car>Taurus</car>
</manufacturer>
<manufacturer name="Volkswagen">
<car>Beetle</car>
<car>Jetta</car>
<car>Passat</car>
<car>Touraeg</car>
</manufacturer>
</cars>
File: Transform.xslt
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.java2s.com"
xmlns:xsd="http://www.w3.org/2000/10/XMLSchema"
version="1.0">
<xsl:output method="xml"/>
<xsl:template match="*">
<xsl:element name="{name(.)}">
<xsl:for-each select="@*">
<xsl:if test="name(.) = 'minOccurs'">
<xsl:if test=". != '1'">
<xsl:attribute name="{name(.)}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:if>
</xsl:if>
<xsl:if test="name(.) = 'maxOccurs'">
<xsl:if test=". != '1'">
<xsl:attribute name="{name(.)}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:if>
</xsl:if>
</xsl:for-each>
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
Output:
<?xml version="1.0" encoding="UTF-8"?><cars xmlns="http://www.java2s.com">
<manufacturer>
<car>Cavalier</car>
<car>Corvette</car>
<car>Impala</car>
<car>Malibu</car>
</manufacturer>
<manufacturer>
<car>Pinto</car>
<car>Mustang</car>
<car>Taurus</car>
</manufacturer>
<manufacturer>
<car>Beetle</car>
<car>Jetta</car>
<car>Passat</car>
<car>Touraeg</car>
</manufacturer>
</cars>
Related examples in the same category