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

Question:

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>
    .
    .
    .
Asked By: Asdoost

||

Answers:

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>
Answered By: Olvin Roght
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.