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.

1
  • If you use the ElemenTree module, you can remove elements with the remove() method on Element objects. See here for details: docs.python.org/2/library/… Commented Aug 7, 2019 at 9:33

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Do you know how i can use it using the library element.tree?
@asdsmk2 I don't have experience with elementTree, but here is some information stackoverflow.com/questions/6847263/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.