【发布时间】:2017-10-10 19:11:57
【问题描述】:
我是 xml 解析的新手。 This xml file 具有以下树:
FHRSEstablishment
|--> Header
| |--> ...
|--> EstablishmentCollection
| |--> EstablishmentDetail
| | |-->...
| |--> Scores
| | |-->...
|--> EstablishmentCollection
| |--> EstablishmentDetail
| | |-->...
| |--> Scores
| | |-->...
但是当我使用 ElementTree 访问它并查找 child 标记和属性时,
import xml.etree.ElementTree as ET
import urllib2
tree = ET.parse(
file=urllib2.urlopen('http://ratings.food.gov.uk/OpenDataFiles/FHRS408en-GB.xml' % i))
root = tree.getroot()
for child in root:
print child.tag, child.attrib
我只得到:
Header {}
EstablishmentCollection {}
我认为这意味着它们的属性是空的。为什么会这样,我如何访问嵌套在 EstablishmentDetail 和 Scores 中的孩子?
编辑
感谢下面的答案,我可以进入树内部,但如果我想检索诸如 Scores 中的值,则失败:
for node in root.find('.//EstablishmentDetail/Scores'):
rating = node.attrib.get('Hygiene')
print rating
并产生
None
None
None
为什么会这样?
【问题讨论】:
标签: python xml tree xml-parsing elementtree