Abhishek
Abhishek

Reputation: 1837

ElementTree parsing in python

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.

Upvotes: 0

Views: 71

Answers (2)

Fredrik H&#229;&#229;rd
Fredrik H&#229;&#229;rd

Reputation: 2925

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.

Upvotes: 1

DSM
DSM

Reputation: 353509

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>

Upvotes: 2

Related Questions