XML和XSLT以及设置命名空间

时间:2009-11-06 12:57:25

标签: xml xslt namespaces

我需要将xmlns添加到此XSLT转换的输出中的根元素。我已尝试添加<xsl:attribute name="xmlns">,但不允许这样做。

有没有人知道如何解决这个问题?

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

    <xsl:template match="/">
            <xsl:variable name="rootElement" select="name(*)"/>
            <xsl:element name="{$rootElement}">
                <xsl:apply-templates select="/*/*"/>
            </xsl:element>
    </xsl:template>

    <xsl:template match="node()"> 
        <xsl:copy> 
                <xsl:copy-of select="@*"/> 
            <xsl:apply-templates select="node()"/> 
        </xsl:copy> 
    </xsl:template>

</xsl:stylesheet>

2 个答案:

答案 0 :(得分:4)

来自the XSLT 1.0 spec

  

xsl:element元素允许使用计算名称创建元素。要创建的元素的扩展名由必需的name属性和可选的namespace属性指定。

因此,您需要声明要在xsl:stylesheet元素上使用的名称空间前缀,然后在创建元素时指定名称空间URI。

为了说明,以下样式表:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:foo="http://example.com/foo">
  <xsl:template match="/">
    <xsl:element name="bar" namespace="http://example.com/foo">element</xsl:element>
  </xsl:template>
</xsl:stylesheet>

产生输出:

<?xml version="1.0" encoding="UTF-8"?>
<foo:bar xmlns:foo="http://example.com/foo">element</foo:bar>

答案 1 :(得分:2)

您不能简单地“添加”命名空间,至少不能在XSLT 1.0中添加。命名空间是输入节点的固定属性。您复制节点,也复制其命名空间。

这意味着您必须创建位于正确名称空间中的 new 节点。如果您不想要前缀,而是需要默认命名空间,则XSL样式表必须位于相同的默认命名空间中。

以下将默认命名空间应用于所有元素节点并复制其余节点:

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns="http://tempuri.org/some/namespace"
>

  <xsl:template match="node() | @*">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="*">
    <xsl:element name="{local-name()}">
      <xsl:apply-templates select="node() | @*" />
    </xsl:element> 
  </xsl:template>

</xsl:stylesheet>

转动

<bla bla="bla">
  <bla />
</bla>

<bla bla="bla" xmlns="http://tempuri.org/some/namespace">
  <bla></bla>
</bla>