'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>
.
.
.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Olvin Roght |
