3

Please help, Python beginner,

after getting all the data from xml, data_list = xmlTree.findall('.//data') e.g here I get 10 rows Now, I need to keep only a few rows for which attribute 'name' values match with elements of another list (inputID) with three IDs inside. e.g. remains only 3 rows whose name attribute match with the list elements

Thank you.

1
  • 1
    +1 for the "Please help, Python beginner" Commented Aug 8, 2012 at 14:45

2 Answers 2

1

You can use a for loop to iterate over each element, then decide if each element should be removed. I used the Python doc ElementTree XML API for reference.

from xml.etree.ElementTree import ElementTree

tree = ElementTree()

# Test input
tree.parse("sample.xml")

# List containing names you want to keep
inputID = ['name1', 'name2', 'name3']

for node in tree.findall('.//data'):
    # Remove node if the name attribute value is not in inputID
    if not node.attrib.get('name') in inputID:
        tree.getroot().remove(node)

# Do what you want with the modified xml
tree.write('sample_out.xml')
Sign up to request clarification or add additional context in comments.

3 Comments

thank you so much...It is exactly what I wanted to do... I already have the module imported but since it's all new to me, do not even know the basics of Python....somehow got new books and tuts to work on since yesterday....funny....thanks again...:-)
Not a problem--glad I could help. I would appreciate if you would accept my answer, though. Thanks.
yes, this is the answer that I actually used with changes according to my need..thanks again..
0

You can remove a node from the tree using

current_node.getparent().remove(current_node)

Comments

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.