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>

目前我的代码看起来像这样,但它不会删除子项,而是将整棵树插入 ide:

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)

输出

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