繁体   English   中英

如何使用 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM