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个步骤:
获取符合条件的元素(Tag==x,Parent Tag==y) 从父级中删除该元素,在该位置放置一个新的子级 将以前的子项添加到新的子项。第一步,我们可以使用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')
未经测试