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

XML跨子节点元素复制需求:将wildlife节点的class复制到library节点

要实现把title为"wildlife"的topic中的元素复制到title为"library"的topic里,这里有两种实用方案供你选择:


方法1:使用XSLT(XML专属转换语言)

XSLT是处理XML结构转换的标准工具,非常适合这类场景。下面的样式表会保留原XML的所有内容,同时完成你需要的元素复制:

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

    <!-- 匹配library主题下的property节点,插入wildlife的class元素 -->
    <xsl:template match="topic[topic-header/title='library']/basis/variant/property">
        <!-- 先复制当前property节点的原有内容 -->
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
            <!-- 复制wildlife主题下的class元素 -->
            <xsl:copy-of select="/node-A/topics/topic[topic-header/title='wildlife']/basis/variant/property/class"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

说明:

  • 身份模板确保原XML的所有节点、属性和文本都被原样保留;
  • 第二个模板精准定位到library主题的property节点,在输出原有内容后,通过<xsl:copy-of>复制wildlife主题下的class元素并插入进去。

方法2:使用Python脚本(灵活可编程)

如果你更习惯用代码来处理,Python的xml.etree.ElementTree模块可以轻松完成这个操作:

import xml.etree.ElementTree as ET
import copy

# 输入XML字符串(如果是文件,用ET.parse('input.xml')即可)
input_xml = """<node-A> <logs>abc</logs> <topics> <topic> <topic-header> <title>wildlife</title> </topic-header> <basis> <variant> <property> <class code="books" description="books" sourceSystem="">books </class> </property> </variant> </basis> </topic> <topic> <topic-header> <title>library</title> </topic-header> <basis> <variant> <property> <x></x> <y></y> <z></z> </property> </variant> </basis> </topic> </topics> </node-A>"""

# 解析XML
root = ET.fromstring(input_xml)

# 找到wildlife主题下的class元素
wildlife_class = root.find(".//topic[topic-header/title='wildlife']/basis/variant/property/class")
# 找到library主题下的property节点
library_property = root.find(".//topic[topic-header/title='library']/basis/variant/property")

# 复制class元素(必须深拷贝,否则会移动原节点而不是复制)
copied_class = copy.deepcopy(wildlife_class)
# 将复制后的元素添加到library的property节点中
library_property.append(copied_class)

# 输出修改后的XML(格式化输出可以借助第三方库如xml.dom.minidom)
output_xml = ET.tostring(root, encoding='unicode')
print(output_xml)

说明:

  • 使用XPath表达式精准定位目标节点,语法简洁直观;
  • 必须使用copy.deepcopy()来复制元素,避免原节点被从wildlife主题中移除;
  • 如果需要更美观的格式化输出,可以用xml.dom.minidom对输出结果进行美化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:14:55