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

How can I transfer the attributes of parent elements to child elements in XML using python?

给定 XML 文件的以下结构:

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

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

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

嗯,你需要找到<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>

你可以帮助我的国家,检查my profile info