Use variable for namespace in XSL transform

This is probably a duplicate, but I did not find the answer from any other posts, so I will continue and ask.

Inside the XSL file, I would like to have variables that will be displayed in namespaces.

Sort of:

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

Then in the template do the following:

<SomeElement xmlns="$some_ns">

I was not lucky to get this job, although it seems pretty simple.

Thank you for your time.

+4
source share
3 answers

To dynamically set namespaces at run time, use the <xsl:element>attribute value template.

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

If you do not need to set dynamic namespaces, declare a prefix for them and use this:

<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>

:

<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>
+7

XSLT 2.0 <xsl:namespace>. , , . , xsl: element xsl: ,

<xsl:element name="local" namespace="{$var}">
+3

Please do not hit me with your feet, nor mine.;)

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" encoding="utf-8"/>
    <xsl:variable name="some_ns" select="'http://something.com/misc/blah/1.0'" />                       
    <xsl:template match="/">
        <!-- variant for output method="text" that doesn't generate xml declaration -->
        <!--xsl:value-of select="'&#60;element xmlns=&#34;'"/>
        <xsl:value-of select="$some_ns"/>
        <xsl:value-of select="'&#34;&#47;&#62;'"/-->
        <xsl:value-of disable-output-escaping="yes" select="'&#60;element xmlns=&#34;'"/>
        <xsl:value-of select="$some_ns"/>
        <xsl:value-of disable-output-escaping="yes" select="'&#34;&#47;&#62;'"/>
    </xsl:template>
</xsl:stylesheet>

produces

<?xml version="1.0" encoding="utf-8"?>
<element xmlns="http://something.com/misc/blah/1.0"/>
+1
source

All Articles