1

Sample xml file:

<root>
   <child1 />
   <child2 bksetname="Default Backup Set" />
   <child3 bksetname="Local Backup Set" />
</root>

Code:

import xml.etree.ElementTree as ET

tr = ET.parse("Scheduler.xml")
for elem in tr.iter():
    print elem.tag , elem.attrib
    if elem.attrib.get('bksetname') == "Default Backup Set":
        elem.remove(elem.tag)

Output:

Entering elem:
self._children.remove(element)
child2
ValueError: list.remove(x): x not in list

I am trying to delete the element by searching the element in file, if it has the attribute I want.I tried this way in my code and getting error in my output as shared. Please tell me how can I do this using xml.etree.ElementTree package.

salmanwahed
  • 9,450
  • 7
  • 32
  • 55
Anuj Bhasin
  • 610
  • 1
  • 8
  • 18

2 Answers2

3

You have to remove it from the element which you are iterating. Here tr is a ElementTree type object. If you want to remove some element from the tree, you can do it by removing it from the root element. Something Like this:

import xml.etree.ElementTree as ET

tr = ET.parse("Scheduler.xml")
for elem in tr.iter():
    print elem.tag , elem.attrib
    if elem.attrib.get('bksetname') == "Default Backup Set":
        tr.getroot().remove(elem)

# for rewriting the file:
tr.write("Scheduler.xml")
salmanwahed
  • 9,450
  • 7
  • 32
  • 55
1

For doing so you need to access item's parent. If you are sure it alwasy one level deep, yo can remove it directly by using:

tr.remove(item)

But if not, you need to create a reverse tree to access parent, like describe Here, Or you can use more powerful library like lxml.

Then you can use xpath and getparent to handle the issue.

The correct way to handle this query is using XPATH:

from lxml import etree
tr = etree.fromstring(open("Scheduler.xml").read())
for item in tr.xpath(//*[@bksetname="Default Backup Set"]):
    item.getparent().remove(item)

Pattern //*[@bksetname="Default Backup Set"] means all element which has attribute bksetname="Default Backup Set". Then we ask for it's parent and remove the element.

Please mention I use lxml instead of ElementTree.

You can use Free OnlineXpath tester for checking XPATH

Community
  • 1
  • 1
Ali Nikneshan
  • 3,500
  • 27
  • 39