简体   繁体   中英

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

Given the following structure of XML file:

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

how can transfer the attributes from parent to child and delete the parent element to get the following structure:

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

Well, you need to find <parent> , then find <child> , copy attributes from <parent> to <child> , append <child> to root node and remove <parent> . Everything is that simple:

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)

Result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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