在Python中使用elementTree搜索和删除element [英] Search and remove element with elementTree in Python
问题描述
我有一个XML文档,我想在其中搜索某些元素,如果它们符合某些条件
,我想删除它们
I have an XML document in which I want to search for some elements and if they match some criteria I would like to delete them
但是,我似乎无法访问该元素的父级,以便可以将其删除
However, I cannot seem to be able to access the parent of the element so that I can delete it
file = open('test.xml', "r")
elem = ElementTree.parse(file)
namespace = "{http://somens}"
props = elem.findall('.//{0}prop'.format(namespace))
for prop in props:
type = prop.attrib.get('type', None)
if type == 'json':
value = json.loads(prop.attrib['value'])
if value['name'] == 'Page1.Button1':
#here I need to access the parent of prop
# in order to delete the prop
谢谢
推荐答案
使用删除
方法删除子元素。要删除元素,您必须调用其父元素的删除
方法。不幸的是, Element
没有提供对其父母的引用,因此,由您来跟踪父子关系(这不利于您使用 elem.findall()
)
You can remove child elements with the according remove
method. To remove an element you have to call its parents remove
method. Unfortunately Element
does not provide a reference to its parents, so it is up to you to keep track of parent/child relations (which speaks against your use of elem.findall()
)
建议的解决方案如下:
root = elem.getroot()
for child in root:
if child.name != "prop":
continue
if True:# TODO: do your check here!
root.remove(child)
PS:请勿使用 prop.attrib.get()
,使用 prop.get()
,如此处。
PS: don't use prop.attrib.get()
, use prop.get()
, as explained here.
这篇关于在Python中使用elementTree搜索和删除element的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!