How is it possible to generate namespaced XML attributes dynamically in XSLT? For example, we can have the following XML document using different attributes, such as attr1:foo or attr2:bar:
<a xmlns="http://example.com/"
xmlns:attr1="http://example.com/attr1#"
xmlns:attr2="http://example.com/attr2#">
<b attr1:foo=""/>
<b attr2:bar=""/>
</a>
Suppose we want to transform the document and change the values of all attributes to .... How should we construct these attributes? A natural option how to go about this would be to use <xsl:attribute>. But what QName should we use as its name attribute? The function name() can return the QName of the attribute as a string. Naïve XSL template might look like this:
<xsl:template match="@*">
<xsl:attribute name="{name()}">...</xsl:attribute>
</xsl:template>
However, since name() returns the QName as string, this solution requires to have predefined the namespace prefix bindings via xmlns in the XSLT (e.g., xmlns:attr1="http://example.com/attr1#").
Then I was wondering if using the namespace attribute of <xsl:attribute> is the way to go:
<xsl:template match="@*">
<xsl:attribute name="{local-name()}"
namespace="{namespace-uri()}">...</xsl:attribute>
</xsl:template>
This solution seems to work, but I think it's hardly best practice in XSLT. Do you know a better solution?