【问题标题】:Add a namespace to elements为元素添加命名空间
【发布时间】:2010-09-13 18:27:24
【问题描述】:

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

【问题讨论】:

    标签: xml xslt namespaces


    【解决方案1】:

    使用 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>
    

    这就是你要找的吗?

    【讨论】:

    • 是的;我在你的帖子之前搜索了一个答案,它基本上是一样的。一个区别是我使用 代替,但我相信它们在功能上是相同的。
    【解决方案2】:

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

    酱料将是identity transform,主要风味将通过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>
    

    个人信息:您好,珍妮·坦尼森。我知道你正在阅读这篇文章。

    【讨论】:

      【解决方案3】:

      这是我目前所拥有的:

      <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 似乎没有削减它)。

      【讨论】:

      • 您没有阅读正确的文档。使用武力,阅读规范,它写得很好,易于理解。
      猜你喜欢
      • 2012-11-25
      • 1970-01-01
      • 2019-11-17
      • 2017-11-27
      • 1970-01-01
      • 2011-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多