【问题标题】:How do I add a namespace to all elements in a node?如何为节点中的所有元素添加命名空间?
【发布时间】:2014-07-18 08:38:33
【问题描述】:

假设我有一些 xml:

<a>
  <b>something</b>
  <c>something</c>
  <d>something</d>
</a>

我希望&lt;a&gt; 的所有子级都以x 命名空间为前缀。目前我有以下实现这一目标:

<xsl:template match="a">
  <a>
    <xsl:apply-templates>
  </a>
</xsl:template>

<xsl:template match="b">
  <x:b><xsl:value-of select="." /></x:b>
</xsl:template>

<xsl:template match="c">
  <x:c><xsl:value-of select="." /></x:c>
</xsl:template>

<xsl:template match="d">
  <x:d><xsl:value-of select="." /></x:d>
</xsl:template>

这可行,但它很麻烦,我必须知道所有孩子的名字是什么。我知道match="*" 语法,但我不知道如何获取* 的名称,所以我可以在模板匹配中添加x。有什么想法吗?

明确地说,我希望将那些 xsl:template 节点替换为单个节点,该节点将在任何节点名称前加上包含 x 命名空间的节点。

【问题讨论】:

    标签: xslt


    【解决方案1】:

    使用local-name(.) 获取节点的本地名称(即没有命名空间的名称),并使用xsl:element 创建具有该名称的元素。使用name(.) 作为属性。应用程序是这样的:

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
      xmlns:z="http://example.com/z">
    
     <xsl:template match="*">
     <xsl:element name="z:{local-name(.)}">
      <xsl:apply-templates select="@*|*|text()"/>
     </xsl:element>
    </xsl:template>
    
    <xsl:template match="@*">
      <xsl:attribute name="{name(.)}"><xsl:value-of select="."/></xsl:attribute>
    </xsl:template>
    
    </xsl:stylesheet>
    

    编辑:添加属性模板。

    【讨论】:

      【解决方案2】:

      这个 XSLT 怎么样?

      <?xml version="1.0" encoding="UTF-8"?>
      <xsl:stylesheet 
          version="1.0"
          xmlns:x="mynamespace"
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
      
        <xsl:template match="*">
          <xsl:element name="x:{name()}">
            <xsl:apply-templates/>
          </xsl:element>
        </xsl:template>
      
      </xsl:stylesheet>
      

      【讨论】:

      • 其实@evil otto(好名字!)的解决方案比我的要好,因为local-name()name() 更合适。不过,在您的命名空间配置中,这两种解决方案是等效的。
      猜你喜欢
      • 2010-09-13
      • 1970-01-01
      • 2014-08-17
      • 2022-07-25
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多