在Python中解析嵌套的XML?

时间:2018-11-25 19:07:02

标签: python xml

我有以下Goodreads回复:

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

我想检索popular_shelves 2nd货架项目。 (索引1)。

尝试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'))

尝试2:

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

2 个答案:

答案 0 :(得分:1)

这就是我从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 货架商品的方式:

shelf

因此,我们可以将./book/popular_shelves下的所有1st项目加载到列表中。然后,使用列表索引访问2nd0等货架项目。

答案 1 :(得分:0)

您可以尝试模块解开,它操作起来非常简单容易,例如:

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}