如何使用python将XML中父元素的属性传递给子元素?

4nkexdtk  于 2022-12-25  发布在  Python
关注(0)|答案(1)|浏览(125)

给定XML文件的以下结构:

<root>
    <parent attr1="foo" attr2="bar">
        <child> something </child>
    </parent>
    .
    .
    .

如何将属性从父元素转移到子元素并删除父元素以获得以下结构:

<root>
    <child attr1="foo" attr2="bar">
    something
    </child>
    .
    .
    .
qyswt5oh

qyswt5oh1#

那么,您需要找到<parent>,然后找到<child>,将属性从<parent>复制到<child>,将<child>附加到根节点并删除<parent>

import xml.etree.ElementTree as ET

xml = '''<root>
    <parent attr1="foo" attr2="bar">
        <child> something </child>
    </parent>
</root>'''

root = ET.fromstring(xml)
parent = root.find("parent")
child = parent.find("child")
child.attrib = parent.attrib
root.append(child)
root.remove(parent)
# next code is just to print patched XML
ET.indent(root)
ET.dump(root)

结果:

<root>
  <child attr1="foo" attr2="bar"> something </child>
</root>

相关问题