【问题标题】:Python - replace root element of one xml file with another root element without its childrenPython - 用另一个没有子元素的根元素替换一个xml文件的根元素
【发布时间】:2021-11-27 08:17:25
【问题描述】:

我有一个看起来像这样的 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)

任何人都知道我该如何实现这一目标?

谢谢!

【问题讨论】:

  • 这能回答你的问题吗? XML: remove child node of a node
  • 不幸的是 noup,因为在这里他知道孩子的标签是什么,但在我的情况下它们正在改变,所以第二次迭代 bar = foo.findall('bar') 在我的情况下不起作用
  • 您只需将attrib2复制到1。看我的回答。

标签: python xml parsing element elementtree


【解决方案1】:

试试下面的(只需复制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>

【讨论】:

  • 这是一个很好的解决方案,但我不断收到:ParseError not well-formed (invalid token): line 1, column 2
  • 如果您复制并粘贴我的解决方案 - 您会收到任何错误吗?请解释一下你是做什么的。
  • 我只是把 root1 = ET.fromstring(xml1) 并用整个路径替换 xml1 这样的文件 ('C:/myPc/blabla/xml1.xml') 并在该行得到错误
  • 现在我已经设法让它运行了,但是属性值只打印在我的控制台中,实际上并没有复制到文件中
  • @John,将已编辑的 XML 保存到您需要的文件中……将 XML 保存到文件中。 root.write()
【解决方案2】:

所以这里是工作代码:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    相关资源
    最近更新 更多