lxml 是 xml 解析之王。我不确定这是否是你要找的,但你可以尝试这样的事情
from lxml import etree as et
# select a parser and make it remove whitespace
# to discard xml file formatting
parser = et.XMLParser(remove_blank_text=True)
# get the element tree of both of the files
src_tree = et.parse('src.xml', parser)
dest_tree = et.parse('dest.xml', parser)
# get the root element "resources" as
# we want to add it a new element
dest_root = dest_tree.getroot()
# from anywhere in the source document find the "string" tag
# that has a "name" attribute with the value of "TXT_T1"
src_tag = src_tree.find('//string[@name="TXT_T1"]')
# append the tag
dest_root.append(src_tag)
# overwrite the xml file
et.ElementTree(dest_root).write('dest.xml', pretty_print=True, encoding='utf-8', xml_declaration=True)
这假定第一个文件称为 src.xml,第二个文件称为 dest.xml。这也假设您需要在其下复制新元素的元素是父元素。如果没有,您可以使用 find 方法找到您需要的父级,或者如果您不知道父级,则搜索带有 'TXT_T2' 的标签并使用 tag.getparent() 获取父级。