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

问题描述:

我有2个xml(它们恰好是android文本资源),第一个是:

I have 2 xmls (they happen to be android text resources), the first one is:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="TXT_T1">AAAA</string>
</resources>

第二个是

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="TXT_T2">BBBB</string>
</resources>

我知道要复制的元素的属性,在我的示例中为TXT_T1.使用python,如何将其复制到其他xml并将其粘贴到TXT_T2后面?

I know the attribute of the element that I want to copy, in my example it's TXT_T1. Using python, how to copy it to the other xml and paste it right behind TXT_T2?

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.