![](/img/trans.png)
[英]How can I iterate through a list of XML files using Python and append certain fields?
[英]Append xml to xml using python.I have two xml files which i need to merge .so is there anyway i can merge both files
誰能告訴我如何使用python附加xml文件
這是我的file1.xml
<?xml version="1.0"?>
<addressbook>
<person>
<name>Eric Idle</name>
<phone type='fix'>999-999-999</phone>
<phone type='mobile'>555-555-555</phone>
<address>
<street>12, spam road</street>
<city>London</city>
<zip>H4B 1X3</zip>
</address>
</person>
</addressbook>
我想將其附加到另一個xml文件
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
是否有任何模塊可以為我做...
我需要的輸出是:
<addressbook>
<person>
<name>Eric Idle</name>
<phone type='fix'>999-999-999</phone>
<phone type='mobile'>555-555-555</phone>
<address>
<street>12, spam road</street>
<city>London</city>
<zip>H4B 1X3</zip>
</address>
</person>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
</addressbook>
現在我需要從文件中讀取xml,但是稍后我需要從服務器獲取xml響應並將其轉換為一個xml文件。因此,如果有人知道它會對我有很大幫助……
編輯 :刪除舊答案,因為問題發生了很大的變化。
使用lxml:
addressbook_xml = """<?xml version="1.0"?>
<addressbook>
<person>
<name>Eric Idle</name>
<phone type='fix'>999-999-999</phone>
<phone type='mobile'>555-555-555</phone>
<address>
<street>12, spam road</street>
<city>London</city>
<zip>H4B 1X3</zip>
</address>
</person>
</addressbook>"""
note_xml = """<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
"""
from lxml import etree
# XML strings to etree
addressbook_root = etree.fromstring(addressbook_xml)
note_root = etree.fromstring(note_xml)
# append the note
addressbook_root.append(note_root)
# print the new addressbook XML document
print etree.tostring(addressbook_root)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.