简体   繁体   English

如何使用 python 将父元素的属性传递给 XML 中的子元素?

[英]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.

相关问题 如何使用 Python ElementTree 从 XML 文件中的不同子级元素中提取相关属性 - how can I extract related attributes from different child level elements from XML file with Python ElementTree 如何递归地遍历 xml 文件并访问子节点/元素并使用 Python 存储它们的数据? - How do I iterate over a xml file recursively and access the child nodes/elements and store their data using Python? 尽管有属性,如何在 Python XML 中的同一父级中加入具有相同标签的元素? - How to join elements with same tag within the same parent in Python XML despite their attributes? 根据子元素的条件删除 XML 父元素 - Python - Remove XML Parent Elements Based on Condition of Child Element - Python 使用Python和lxml检索XML父级和子级属性 - Retrieve XML parent and child attributes using Python and lxml 如果子项不在其中,则 Python XML 删除元素 - Python XML remove elements if a child is not in it 如何遍历 XML Python 中的子元素的子元素? - How to iterate over child of child elements in XML Python? 如何计算 python 列表中的 XML 字符串元素? - How can I count XML string elements in a python list? 如何使用 BeautifulSoup 访问命名空间 XML 元素? - How can I access namespaced XML elements using BeautifulSoup? 如何创建子元素仅依赖于父元素的 Python 树 - How to create a Python tree where the child elements depend only on the parent
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM