Search code examples
xsltnamespaceselement

Is there a way to add attributes with namespaces when creating an element in XSLT?


I'm trying to create an XSLT file with another one,

<xsl:element name="xsl:stylesheet">
      <xsl:attribute name="version">1.0</xsl:attribute>
      <xsl:attribute name="xmlns:msxsl">urn:schemas-microsoft-com:xslt</xsl:attribute>
      <xsl:attribute name="xlink">http://www.w3.org/1999/xlink</xsl:attribute>
      <xsl:attribute name="exclude-result-prefixes">msxsl</xsl:attribute>

        <xsl:apply-templates select="Root"/>
    </xsl:element>

The second attribute has a namespace "xmlns" which throws an error: Prefix is not defined.

It works fine without the namespace as in the third attribute, xlink.

How can I specify the namespace then?

Thank you


Solution

  • Here is a simplified version of the last suggestion in Michael Kay's answer:

    <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" 
    xmlns:xlink="http://www.w3.org/1999/xlink">
    <xsl:output method="xml" indent="yes"/>
    
    <xsl:template match="/">
        <xsl:element name="xsl:stylesheet">
            <xsl:copy-of select="document('')/xsl:stylesheet/namespace::*"/>
            <xsl:attribute name="version">1.0</xsl:attribute>
            <xsl:attribute name="exclude-result-prefixes">msxsl xlink</xsl:attribute>
            <!-- more here -->
        </xsl:element> 
    </xsl:template> 
    
    </xsl:stylesheet>
    

    The result:

    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.0" exclude-result-prefixes="msxsl xlink"/>
    

    However this does not work with Xalan 2.7.2 and I am not able to test it with a MS processor (I don't think the documentfunction will work with an online tester). You might be better off using a namespace alias.