John Lippson
John Lippson

Reputation: 1329

Parsing nested XML in Python?

I have the following goodreads response:

<GoodreadsResponse>
   <Request>
   </Request>
   <book>
    <popular_shelves>
        <shelf name="test" other="1"/>
        <shelf name="test2" other="2"/>
    </popular_shelves/>
   </book>
</GoodreadsResponse>

I want to retrieve the popular_shelves 2nd shelf item. (index 1).

Attempt 1:

from xml.etree import ElementTree as ET

  root = ET.parse(urllib.urlopen(baseEndpoint+bookName)).getroot()
  for atype in root.findall('book/popular_shelves'):
    print(atype.get('shelf'))

Attempt 2:

  genre = root.find('book').findall('popular_shelves')[0].findall('shelf')
  print genre[0].text

Upvotes: 0

Views: 67

Answers (2)

panda912
panda912

Reputation: 396

you can try module untangle, it simple and easy to work with, for example:

In [95]: from untangle import parse

In [96]: payload = '''
    ...: <GoodreadsResponse>
    ...:    <Request>
    ...:    </Request>
    ...:    <book>
    ...:     <popular_shelves>
    ...:         <shelf name="test" other="1"/>
    ...:         <shelf name="test2" other="2"/>
    ...:     </popular_shelves>
    ...:    </book>
    ...: </GoodreadsResponse>
    ...: '''

In [97]: obj = parse(payload)

In [98]: shelf1 = obj.GoodreadsResponse.book.popular_shelves.shelf[1]

In [99]: vars(shelf1)
Out[99]:
{'_attributes': {u'name': u'test2', u'other': u'2'},
 '_name': u'shelf',
 'cdata': '',
 'children': [],
 'is_root': False}

Upvotes: 0

singleton
singleton

Reputation: 111

This is how I got the 2nd shelf item from popular_shelves:

import xml.etree.ElementTree as ET

payload = '''
<GoodreadsResponse>
   <Request>
   </Request>
   <book>
    <popular_shelves>
        <shelf name="test" other="1"/>
        <shelf name="test2" other="2"/>
    </popular_shelves>
   </book>
</GoodreadsResponse>
'''

root = ET.fromstring(payload)
shelves = root.findall("./book/popular_shelves/shelf") # this will get you the list of shelves
print shelves[1].get('name') # fetching the name of 2nd shelf item

So, we can load all shelf items under ./book/popular_shelves into a list. And, then use the list index to access 1st, 2nd, etc. shelf items.

Upvotes: 1

Related Questions