使用ElementTree将父标记添加到嵌套结构(Python) [英] Adding a parent tag to a nested structure with ElementTree (Python)

查看:0
本文介绍了使用ElementTree将父标记添加到嵌套结构(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have the following structure

<root>
  <data>
     <config>
        CONFIGURATION
     <config>
  </data>

</root>

使用Python的ElementTree模块,我想将父元素添加到<config>标记为

<root>
  <data>
    <type>
      <config>
        CONFIGURATION
      <config>
    </type>
  </data>

</root>
此外,该XML文件还可能在其他地方有其他配置标记,但我只对出现在数据标记下的那些标记感兴趣。

推荐答案

归结为~3个步骤:

  1. 获取符合条件的元素(Tag==x,Parent Tag==y)
  2. 从父级中删除该元素,在该位置放置一个新的子级
  3. 将以前的子项添加到新的子项。

第一步,我们可以使用this answer。因为我们知道以后需要父母,所以让我们在搜索中也保留这一点。

def find_elements(tree, child_tag, parent_tag):
    parent_map = dict((c, p) for p in tree.iter() for c in p)
    for el in tree.iter(child_tag):
        parent = parent_map[el]
        if parent.tag == parent_tag:
            yield el, parent

第二步和第三步很相关,我们可以一起做。

def insert_new_els(tree, child_tag, parent_tag, new_node_tag):
    to_replace = list(find_elements(tree, child_tag, parent_tag))
    for child, parent in to_replace:
        ix = list(parent).index(child)
        new_node = ET.Element(new_node_tag)
        parent.insert(ix, new_node)
        parent.remove(child)
        new_node.append(child)

您的树将被原地修改。 现在的用法很简单:

tree = ET.parse('some_file.xml')
insert_new_els(tree, 'config', 'data', 'type')
tree.write('some_file_processed.xml')

未经测试

这篇关于使用ElementTree将父标记添加到嵌套结构(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆