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()獲取父項。
它的工作幾乎完美,除了添加的行不縮進 –
我更新了帖子。您需要中斷XML文件的格式,並且可以通過創建解析器並將其設置爲刪除空白文本來完成。請記住在解析xml文件時傳遞解析器。原始代碼仍然有效,並且文檔的結構是有效的。但是,如果這讓你感到困擾,新代碼還會處理格式。 – NotNone