0

I have an xml file that is containing a root element, and sub elements of sub elements.

For example:

<root>
    <subRoot>
    <Modified name="Set" text="Bla">
      <Action name="Bla2"/>
    </Modified>
</subRoot>
</root>

If i want to delete all of the Action tags under Modified- How can i do that? Thanks.

  • If you use the ElemenTree module, you can remove elements with the remove() method on Element objects. See here for details: https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.remove – Hkoof Aug 07 '19 at 09:33

1 Answers1

0

You can use various libraries, this example is using beautifulsoup:

data = '''<root>
    <subRoot>
    <Modified name="Set" text="Bla">
      <Action name="Bla2"/>
    </Modified>
</subRoot>
</root>'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(data, 'xml')

# selects all tags <Action> under <Modified>
for tag in soup.select('Modified Action'):
    tag.extract() # delete it!

print(soup.prettify())

Prints:

<?xml version="1.0" encoding="utf-8"?>
<root>
 <subRoot>
  <Modified name="Set" text="Bla">
  </Modified>
 </subRoot>
</root>
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • Thanks. Do you know how i can use it using the library element.tree? – asdsmk2 Aug 07 '19 at 11:23
  • @asdsmk2 I don't have experience with elementTree, but here is some information https://stackoverflow.com/questions/6847263/search-and-remove-element-with-elementtree-in-python – Andrej Kesely Aug 07 '19 at 11:27