Python——一个xml文件的根元素替换为另一个根元素没有孩子



我有一个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)

有人知道我怎么才能做到这一点吗?

谢谢!

尝试以下操作(只需复制属性)

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)

相关内容