使用 ElementTree (Python) 将父标签添加到嵌套结构

Adding a parent tag to a nested structure with 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. 从 parent 中删除那个元素,在那个地方放一个新的 child
  3. 将原来的child添加到新的child。

第一步,我们可以使用this answer。因为我们知道我们稍后会需要 parent,所以让我们在搜索中也保留它。

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')

未测试