簡體   English   中英

如何使用python將元素從一個xml復制到另一個xml

[英]How to copy element from one xml to another xml with python

我有 2 個 xml(它們恰好是 android 文本資源),第一個是:

<?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后面?

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() 獲取父級。

這僅適用於您的簡單示例:

>>> 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM