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
Is there a way I can do this?
Thanks
You can remove child elements with the according
removemethod. To remove an element you have to call its parentsremovemethod. UnfortunatelyElementdoes 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 ofelem.findall())A proposed solution could look like this:
PS: don’t use
prop.attrib.get(), useprop.get(), as explained here.