【问题标题】:How can I transfer the attributes of parent elements to child elements in XML using python?如何使用 python 将父元素的属性传递给 XML 中的子元素?
【发布时间】:2022-12-24 22:59:30
【问题描述】:

给定以下 XML 文件结构:

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

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

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

【问题讨论】:

    标签: python xml xml.etree


    【解决方案1】:

    那么,您需要找到&lt;parent&gt;,然后找到&lt;child&gt;,将属性从&lt;parent&gt;复制到&lt;child&gt;,将&lt;child&gt;附加到根节点并删除&lt;parent&gt;。一切都那么简单:

    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>
    

    【讨论】:

    • 显然 ET 没有 indent 属性。 AttributeError: module 'xml.etree.ElementTree' has no attribute 'indent' 谢谢你的回答。
    • @Asdoost,从 python 3.9 开始;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    相关资源
    最近更新 更多