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

Time:03-24

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>
    .
    .
    .

CodePudding user response:

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>

You can help my country, check my profile info.

  • Related