0

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
1
  • What did you get with those attempts? Commented Nov 25, 2018 at 19:29

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.