1

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?

1 Answer 1

2

It depends on what do you know about the source document's structure:

  • If you know the namespaces used and their prefix bindings, then declare them in your stylesheet and use what you called a "naïve XSL template".

  • Otherwise copy the namespace (URI), as shown in your second template.


Note also that you can combine the two as follows:

<xsl:template match="@*">
    <xsl:attribute name="{name()}" namespace="{namespace-uri()}">...</xsl:attribute>
</xsl:template>

With some processors (e.g. Saxon 6.5) this will ensure that the original prefixes are re-used in the result; other processors (e.g. libxslt and Xalan) will do that anyway.

Sign up to request clarification or add additional context in comments.

3 Comments

I don't know the namespace prefix bindings in advance. This is why I want to create the namespaced attributes dynamically.
Then I don't know of a better solution than your second template. Why do you think it's not best practice?
OK, I just wasn't sure if it's idiomatic XSLT. I thought there's a simpler way how to do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.