Here's the full stylesheet you need (since the namespaces are important):
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:z="foo">
<xsl:template match="root">
<root>
<xsl:apply-templates />
</root>
</xsl:template>
<xsl:template match="z:row">
<xsl:variable name="A" select="@A" />
<xsl:for-each select="@*[local-name() != 'A']">
<z:row A="{$A}">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="." />
</xsl:attribute>
</z:row>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
I much prefer using literal result elements (eg <z:row>
) rather than <xsl:element>
and attribute value templates (those {}
s in attribute values) rather than <xsl:attribute>
where possible as it makes the code shorter and makes it easier to see the structure of the result document that you're generating. Others prefer <xsl:element>
and <xsl:attribute>
because then everything is an XSLT instruction.
If you're using XSLT 2.0, there are a couple of syntactic niceties that help, namely the except
operator in XPath and the ability to use a select
attribute directly on <xsl:attribute>
:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs"
xmlns:z="foo">
<xsl:template match="root">
<root>
<xsl:apply-templates />
</root>
</xsl:template>
<xsl:template match="z:row">
<xsl:variable name="A" as="xs:string" select="@A" />
<xsl:for-each select="@* except @A">
<z:row A="{$A}">
<xsl:attribute name="{local-name()}" select="." />
</z:row>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>