How does one use XSLT to output the name of an element or an attribute?
Created May 4, 2012
Peter Ciuffetti What you need is something like this:
<xsl:template match="root"> <result> <xsl:for-each select="*"> <xsl:element name="{local-name(@*)}"> <xsl:attribute name="{local-name()}"> <xsl:value-of select="@*"/> </xsl:attribute> </xsl:element> </xsl:for-each> </result> </xsl:template>This uses the local-name() function of XPATH to obtain the name of the element and the name of the first attribute in that element. It will transform:
<root> <a b="c"/> <d e="f"/> <g h="i"/> </root>Into...
<result> <e d="f"></e> <h g="i"></h> </result>Note: When you pass local-name a node set (like @*), it returns only the name of the first node in document order. So you can't use this trick to obtain the name of a second or subsequent attribute.