首页 文章

Xslt生成Xslt:设置根命名空间

提问于
浏览
2

我使用XSLT作为各种组件的“代码生成器”,包括其他XSLT . 例如,我有一个查询,为表生成MSSQL sys.columns行的XML输出,并希望生成一个XSLT,其中包含一个表,每个行都有一列 .

所以我想生成以下XSLT:

<xsl:stylesheet version="1.0" xmlns:format="urn:qbo3-formatting" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  ...
</xsl:stylesheet>

我使用类似'generator'的XSLT生成上面的XSLT:

<xsl:element name="xsl:stylesheet">
  <xsl:attribute name="version">1.0</xsl:attribute>
  <xsl:attribute name="format" namespace="http://www.w3.org/XML/1998/namespace" >urn:qbo3-formatting</xsl:attribute>
  ...
</xsl:element>

问题是这个'生成器'XSLT产生:

<xsl:stylesheet version="1.0" xml:format="urn:qbo3-formatting" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  ...
</xsl:stylesheet>

注意 xml:format 而不是所需的 xmlns:format .

根据W3C,“xmlns”被保留并绑定到“http://www.w3.org/2000/xmlns/” . 如果我尝试使用此命名空间创建上面的format属性,我会收到一个错误:

Elements and attributes cannot belong to the reserved namespace 'http://www.w3.org/2000/xmlns/'.

关于解决方案的任何建议?

提前致谢,

埃里克

2 回答

  • 0

    This is exactly the main usecase for the xsl:namespace-alias instruction

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:format="some:format"
     xmlns:xxx="xxx">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
    
     <xsl:namespace-alias stylesheet-prefix="xxx"
                          result-prefix="xsl"/>
    
     <xsl:template match="/">
        <xxx:stylesheet version="1.0"
             xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
             xmlns:format="some:format"
         >
    
          <xxx:template match="node()|@*">
            <xxx:copy>
              <xxx:apply-templates select="node()|@*"/>
             </xxx:copy>
          </xxx:template>
        </xxx:stylesheet>
    
     </xsl:template>
    </xsl:stylesheet>
    

    当此转换应用于任何XML文档(未使用)时,将生成所需结果(包含所有所需属性和命名空间的新样式表):

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                    xmlns:format="some:format">
      <xsl:template match="node()|@*">
        <xsl:copy>
          <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
      </xsl:template>
    </xsl:stylesheet>
    

    Do note :每当转换生成另一个XSLT样式表时,避免使用 xsl:element 并且更喜欢 xsl:namespace-alias .

  • 1

    试试这个:

    <xsl:element name="xsl:stylesheet">
      <xsl:attribute name="version">1.0</xsl:attribute>
      <xsl:namespace name="format" select="'urn:qbo3-formatting'"/>
    </xsl:element>
    

    或者,不是显式输出XML命名空间,而是允许XSLT在使用该命名空间的节点后自动生成XML命名空间 . 如果没有元素使用 urn:qbo3-formatting ,则不需要命名空间声明 .

相关问题