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

如何用XSLT与XPath将指定XML标签重命名为新标签?

用XSLT+XPath实现XML标签重命名(保留子元素结构)

示例输入XML

<root>
  <bcaExercise>
    <title>代数练习题</title>
    <question>求解方程x²-4=0</question>
    <answer>x=2或x=-2</answer>
  </bcaExercise>
  <otherElement>
    <content>其他内容</content>
  </otherElement>
</root>

实现标签转换的XSLT代码

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <!-- 默认模板:原样复制所有未指定转换的节点、属性和文本 -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <!-- 精准匹配目标标签bcaExercise,重命名为exerciseBca -->
  <xsl:template match="bcaExercise">
    <exerciseBca>
      <!-- 复制原标签的所有属性和子节点,保留原有结构 -->
      <xsl:apply-templates select="@*|node()"/>
    </exerciseBca>
  </xsl:template>
</xsl:stylesheet>

关键逻辑说明

  • 默认模板:match="@*|node()"会匹配XML中所有属性、元素、文本节点等,通过<xsl:copy>复制节点本身,再递归处理子节点,确保未指定转换的内容完全保留原样。
  • 目标标签匹配:match="bcaExercise"精准定位需要重命名的元素,创建新标签<exerciseBca>后,通过<xsl:apply-templates>把原标签的所有属性和子节点都导入新标签内,实现仅修改标签名、保留子结构的需求。

转换后输出XML

<root>
  <exerciseBca>
    <title>代数练习题</title>
    <question>求解方程x²-4=0</question>
    <answer>x=2或x=-2</answer>
  </exerciseBca>
  <otherElement>
    <content>其他内容</content>
  </otherElement>
</root>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 09:30:50