我有一个带有非命名空间元素的XML文档,我想使用XSLT向它们添加命名空间。大多数元素都在命名空间A中;一些将在命名空间B中。我该怎么做?

有帮助吗?

解决方案

使用foo.xml

<foo x="1">
    <bar y="2">
        <baz z="3"/>
    </bar>
    <a-special-element n="8"/>
</foo>

和foo.xsl

    <xsl:template match="*">
        <xsl:element name="{local-name()}" namespace="A" >
            <xsl:copy-of select="attribute::*"/>
            <xsl:apply-templates />
        </xsl:element>
    </xsl:template>

    <xsl:template match="a-special-element">
        <B:a-special-element xmlns:B="B">
            <xsl:apply-templates match="children()"/>
        </B:a-special-element>
    </xsl:template>

</xsl:transform>

我得到了

<foo xmlns="A" x="1">
    <bar y="2">
        <baz z="3"/>
    </bar>
    <B:a-special-element xmlns:B="B"/>
</foo>

这是你正在寻找的吗?

其他提示

这个食谱需要两个主要成分。

酱料将是身份转换,主要风味将由 namespace 属性赋予 xsl:element

以下未经测试的代码应将 http://example.com/ 命名空间添加到所有元素中。

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

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

个人信息:你好,Jeni Tennison。我知道你在读这篇文章。

这是我到目前为止所拥有的:

<xsl:template match="*">
    <xsl:element name="{local-name()}" namespace="A" >
        <xsl:apply-templates />
    </xsl:element>
</xsl:template>

<xsl:template match="a-special-element">
    <B:a-special-element xmlns:B="B">
      <xsl:apply-templates />
    </B:a-special-element>
</xsl:template>

这几乎有效;问题是它不是复制属性。从我以前读过的内容来看,xsl:element没有办法按原样复制元素中的所有属性(use-attribute-sets似乎不会删除它)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top