0

I have xml of the form

<root>
  <tag1>   </tag1>
  <tag2>   </tag2>
  <tag3>   </tag3>

  <tag1>   </tag1>
  <tag2>   </tag2>
  <tag3>   </tag3>
</root>

I need to parse the xml in the order

tag1 -> tag2 -> tag3 -> tag1 -> tag2 -> tag3 

Currently I'm using

root = tree.getroot()
for data in root.findall('tag1')
    do_operations(data)
for data in root.findall('tag2')
    do_operations(data)

But this approach is giving me and that's obvious

tag1 -> tag1 -> tag2 -> tag2 -> tag3 -> tag3

which is not what I want.

Can you suggest an optimum method in which i can pasrse the XML in the desired manner. tag1 , tag2, tag3 are repeated a lot in the same order as given above.

2
  • What module/library are you using?? Commented Mar 28, 2013 at 9:46
  • @Schoolboy ElementTree? Commented Mar 28, 2013 at 9:54

2 Answers 2

2

IIUC, can't you simply loop over root itself?

>>> for data in root:
...     print data
...     
<Element tag1 at 0x102dea7d0>
<Element tag2 at 0x102dea8c0>
<Element tag3 at 0x102dd6d20>
<Element tag1 at 0x102dea7d0>
<Element tag2 at 0x102dea8c0>
<Element tag3 at 0x102dd6d20>
Sign up to request clarification or add additional context in comments.

4 Comments

@Abhishek: those are just the hex versions of the results of id(), as a way to distinguish tags with the same name just from the __repr__.
What if I have them repeating 100 times in the XML. I cannot write them in this fashion
@Abhishek: I don't understand. I didn't write those, those are the results of print data. Instead of for data in root.findall('tag1'):, just use for data in root:, is the point.
Ok got you now. I thought they have to be hardcoded in program. Got your point.
1

You can iterate over the children instead of using find:

for child in root:
    do operations...

If you do different operations to different tags, you can use child.tag to determine what to do:

for child in root:
    if child.tag == 'tag1':
       do operations
    elif child.tag == 'tag2':
       do other operations
    ...

Or you could put the operations in a dict and avoid the if-elif-else incantation.

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.