问题
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>
and the second is
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="TXT_T2">BBBB</string>
</resources>
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?
回答1:
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)
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.
回答2:
This will work only for your simple example:
>>> from xml.dom.minidom import parseString, Document
>>> def merge_xml(dom1, dom2):
node_to_add = None
dom3 = Document()
for node_res in dom1.getElementsByTagName('resources'):
for node_str in node_res.getElementsByTagName('string'):
if 'TXT_T1' == node_str.attributes.values()[0].value:
node_to_add = node_str
break
for node_res in dom2.getElementsByTagName('resources'):
node_str3 = dom3.appendChild(node_res)
for node_str in node_res.getElementsByTagName('string'):
node_str3.appendChild(node_str)
if 'TXT_T2' in node_str.attributes.values()[0].value and node_to_add is not None:
node_str3.appendChild(node_to_add)
return dom3.toxml()
>>> dom2 = parseString('''<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="TXT_T2">BBBB</string>
</resources>''')
>>> dom1 = parseString('''<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="TXT_T1">AAAA</string>
</resources>''')
>>> print merge_xml(dom1, dom2)
<?xml version="1.0" ?><resources>
<string name="TXT_T2">BBBB</string><string name="TXT_T1">AAAA</string></resources>
来源:https://stackoverflow.com/questions/18489562/how-to-copy-element-from-one-xml-to-another-xml-with-python