在 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
单身人士

这就是我2ndpopular_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到列表中。而且,然后用列表索引访问1st2nd等现货产品。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在python中解析嵌套的xml

来自分类Dev

在Python中解析嵌套和复杂的XML

来自分类Dev

通过Python中的深层嵌套XML文件进行解析

来自分类Dev

解析嵌套的XML文件并获取python中先前标记的值

来自分类Dev

在python中解析XML

来自分类Dev

在Python中解析XML

来自分类Dev

XML解析Python ElementTree-嵌套循环

来自分类Dev

Python中的嵌套XML标签

来自分类Dev

通过python中的xml解析

来自分类Dev

通过python中的xml解析

来自分类Dev

在python中解析xml文件

来自分类Dev

在python中解析嵌套函数

来自分类Dev

使用jaxb解析xml中的嵌套元素

来自分类Dev

在Dart / Flutter中解析嵌套的XML

来自分类Dev

在sencha touch 2中解析嵌套的XML

来自分类Dev

解析R中的非嵌套XML标签

来自分类Dev

Python - XML 解析不适用于嵌套的 for 循环

来自分类Dev

在Python中检测XML标签的错误嵌套

来自分类Dev

在python中解析XML以获取数字

来自分类Dev

从python中的xml文件解析数据

来自分类Dev

在python中解析xml文件的数据

来自分类Dev

在python中解析xml文档(在URL上)

来自分类Dev

使用python解析XML中的同名标签

来自分类Dev

Python中的大型XML文件解析

来自分类Dev

在Python中解析XML的最快方法

来自分类Dev

python中的解析器XML

来自分类Dev

如何在python中解析xml?

来自分类Dev

Python解析XML中的流程指令

来自分类Dev

在XML python中解析子元素