簡體   English   中英

Python - 用另一個沒有子元素的根元素替換一個 xml 文件的根元素

[英]Python - replace root element of one xml file with another root element without its children

我有一個 xml 文件,看起來像這樣,XML1:

<?xml version='1.0' encoding='utf-8'?>
<report>
</report>

另一個是這樣的,XML2:

<?xml version='1.0' encoding='utf-8'?>
<report attrib1="blabla" attrib2="blabla" attrib3="blabla" attrib4="blabla" attrib5="blabla" >
    <child1>  
        <child2> 
            ....
        </child2>
    </child1>
</report>

我需要替換並放置沒有子元素的 XML2 的根元素,因此 XML1 看起來像這樣:

<?xml version='1.0' encoding='utf-8'?>
<report attrib1="blabla" attrib2="blabla" attrib3="blabla" attrib4="blabla" attrib5="blabla">
</report>

目前我的代碼看起來像這樣,但它不會刪除子項,而是將整棵樹放在里面:

source_tree = ET.parse('XML2.xml')
source_root = source_tree.getroot()

report = source_root.findall('report') 

for child in list(report):
     report.remove(child)
     source_tree.write('XML1.xml', encoding='utf-8', xml_declaration=True)

任何人都有 ide 我怎樣才能做到這一點?

謝謝!

嘗試以下(只需復制attrib

import xml.etree.ElementTree as ET


xml1 = '''<?xml version='1.0' encoding='utf-8'?>
<report>
</report>'''

xml2 = '''<?xml version='1.0' encoding='utf-8'?>
<report attrib1="blabla" attrib2="blabla" attrib3="blabla" attrib4="blabla" attrib5="blabla" >
    <child1>  
        <child2> 
        </child2>
    </child1>
</report>'''

root1 = ET.fromstring(xml1)
root2 = ET.fromstring(xml2)

root1.attrib = root2.attrib

ET.dump(root1)

output

<report attrib1="blabla" attrib2="blabla" attrib3="blabla" attrib4="blabla" attrib5="blabla">
</report>

所以這是工作代碼:

source_tree = ET.parse('XML2.xml')
source_root = source_tree.getroot()

dest_tree = ET.parse('XML1.xml')
dest_root = dest_tree.getroot()

dest_root.attrib = source_root.attrib
dest_tree.write('XML1.xml', encoding='utf-8', xml_declaration=True)

暫無
暫無

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

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