You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用XSLT移除XML中的根元素?

XSLT处理带命名空间的XML问题

问题详情

输入XML(包含命名空间):

<Root xmlns="http://www.example.com/mdm/readingxml/2011/07">
  <child1>child1</child1>
  <child2>child2</child2>
  <child3>child3</child3>
  <child4>child4</child4>
</Root>

预期输出XML:

<child1>child1</child1>
<child2>child2</child2>
<child3>child3</child3>
<child4>child3</child4>

当前使用的XSLT(未达到预期效果):

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

<!-- template for the document element -->
<xsl:template match="/*">
  <xsl:apply-templates select="node()" />
</xsl:template>

问题原因

输入XML里的所有元素都属于http://www.example.com/mdm/readingxml/2011/07命名空间,但当前XSLT未声明该命名空间,导致模板无法匹配到目标元素;同时缺少修改child4文本内容的逻辑。

修正后的XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:ns="http://www.example.com/mdm/readingxml/2011/07">
  <!-- 身份模板:默认复制所有节点和属性 -->
  <xsl:template match="node() | @*">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*" />
    </xsl:copy>
  </xsl:template>

  <!-- 匹配带命名空间的根节点,不复制根节点,直接处理其子元素 -->
  <xsl:template match="ns:Root">
    <xsl:apply-templates select="node()" />
  </xsl:template>

  <!-- 替换child4的文本内容为child3 -->
  <xsl:template match="ns:child4/text()">
    <xsl:text>child3</xsl:text>
  </xsl:template>
</xsl:stylesheet>

关键修改点

  • 声明命名空间:在xsl:stylesheet标签里将输入XML的命名空间绑定到前缀ns,让XSLT能识别目标元素。
  • 精准匹配根节点:把原来的match="/*"改成match="ns:Root",确保只处理目标根节点。
  • 添加文本替换逻辑:新增模板匹配ns:child4的文本节点,替换成预期内容。

内容的提问来源于stack exchange,提问作者Nilesh Jha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 17:55:13