Search code examples
xmlxsltxslt-2.0

Cannot retrieve value using AVT in attributes prefaced by xmlns


I have a xslt stylesheet that looks like this. I need to use set up attribute values using parameters. I intend to use AVT for this. However I find that AVTs are not replaced in attributes prefaced with "xmlns". I have indicated the issues in the xslt below. Any suggestions will be very welcome.

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs xsl" version="2.0">
    <xsl:output omit-xml-declaration="no" indent="yes" />
    <xsl:variable name="type" select="'mytype'"/>
    <xsl:template match="Root"> 

        <xsl:comment select="$type" /> <!-- Getting output here -->

        <out xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
            xmlns:a="{$type}" <!-- Not getting output here -->
            b="{$type}">      <!-- Getting output here -->

            <nestOut xmlns:nc="{$type}" <!-- Not getting output here -->
                     xsi:na="{$type}"   <!-- Getting output here -->
                     nb="{$type}">Test  <!-- Getting output here -->
            </nestOut>
        </out>
    </xsl:template>
</xsl:stylesheet>

Solution

  • A namespace declaration is not an attribute. You can use the xsl:namespace instruction to produce a namespace node with a calculated namespace-URI. Consider this simplified example:

    XSLT 2.0

    <xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    
    <xsl:variable name="my-URI" select="'http:example.com/mynamespace'"/>
    
    <xsl:template match="/">
        <out>
            <xsl:namespace name="a">
                <xsl:value-of select="$my-URI"/>
            </xsl:namespace>
        </out>
    </xsl:template>
    
    </xsl:stylesheet>
    

    Result

    <?xml version="1.0" encoding="UTF-8"?>
    <out xmlns:a="http:example.com/mynamespace"/>