[英]How can I transfer the attributes of parent elements to child elements in XML using python?
Given the following structure of XML file:给定以下 XML 文件结构:
<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>
.那么,您需要找到
<parent>
,然后找到<child>
,将属性从<parent>
复制到<child>
,将<child>
附加到根节点并删除<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.