use*_*096 0 python xml elementtree
I have the following structure
<root>
<data>
<config>
CONFIGURATION
<config>
</data>
</root>
Run Code Online (Sandbox Code Playgroud)
使用 Python 的 ElementTree 模块,我想添加一个父元素来<config>标记为
<root>
<data>
<type>
<config>
CONFIGURATION
<config>
</type>
</data>
</root>
Run Code Online (Sandbox Code Playgroud)
此外,xml 文件可能在其他地方有其他配置标签,但我只对出现在数据标签下的那些感兴趣。
这归结为〜3个步骤:
对于第一步,我们可以使用这个答案。因为我们知道我们稍后会需要父对象,所以让我们在搜索中也保留它。
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
Run Code Online (Sandbox Code Playgroud)
第二步和第三步非常相关,我们可以一起做。
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)
Run Code Online (Sandbox Code Playgroud)
您的树将被修改到位。现在的用法很简单:
tree = ET.parse('some_file.xml')
insert_new_els(tree, 'config', 'data', 'type')
tree.write('some_file_processed.xml')
Run Code Online (Sandbox Code Playgroud)
未经测试