Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a variable for a namespace in an XSL transform

Tags:

xml

xslt

xslt-2.0

This is probably a duplicate, but I haven't found the answer from any other posts so I will go ahead and ask.

Inside an XSL file, I'd like to have variables that are the namespaces that will be output.

Something like:

<xsl:variable name="some_ns" select="'http://something.com/misc/blah/1.0'" />

Then in a template, do this:

<SomeElement xmlns="$some_ns">

I have had no luck getting this work, even though it seems rather simple.

Thanks for your time.

like image 291
chrismead Avatar asked Nov 06 '13 23:11

chrismead


2 Answers

To set namespaces dynamically at runtime, use <xsl:element> and an attribute value template.

<xsl:element name="SomeElement" namespace="{$some_ns}">
  <!-- ... -->
</xsl:element>

If you don't need to set dynamic namespaces, declare a prefix for them and use that:

<xsl:stylesheet 
  version="2.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  xmlns:foo="http://something.com/misc/blah/1.0"
>
  <xsl:template match="/">
    <foo:SomeElement>
      <!-- ... -->
    </foo:SomeElement>
  </xsl:template>
</xsl:stylesheet>

or even mark the namespace as default:

<xsl:stylesheet 
  version="2.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
  xmlns="http://something.com/misc/blah/1.0"
>
  <xsl:template match="/">
    <SomeElement>
      <!-- ... -->
    </SomeElement>
  </xsl:template>
</xsl:stylesheet>
like image 156
Tomalak Avatar answered Sep 22 '22 18:09

Tomalak


In XSLT 2.0 you can use <xsl:namespace>. But it's only needed in the rare case where you need to generate a namespace declaration that isn't used in the names of elements and attributes. To generate a dynamic namespace for the names of constructed elements and attributes, use the namespace attribute of xsl:element or xsl:attribute, which is an attribute value template so it can be written

<xsl:element name="local" namespace="{$var}">
like image 38
Michael Kay Avatar answered Sep 21 '22 18:09

Michael Kay