且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用python将元素从一个xml复制到另一个xml

更新时间:2023-11-27 22:26:28

lxml是xml解析之王.我不确定这是否是您要寻找的东西,但是您可以尝试这样的事情

lxml is the king of xml parsing. I'm not sure if this is what you are looking for, but you could try something like this

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()获取父对象.

This assumes, that the first file is called src.xml and the second dest.xml. This also assumes that the element under which you need to copy the new element is the parent element. If not, you can use the find method to find the parent you need or if you don't know the parent, search for the tag with 'TXT_T2' and use tag.getparent() to get the parent.