【发布时间】:2013-08-27 19:23:46
【问题描述】:
我在解析特定样式的 XML 时遇到了困难。
XML 文件如下所示:
<channels>
<genre type = blah1>
<channel name="Channel 1">
<show>
<title>hello</title>
</show>
</channel>
<channel name="Channel 2">
<show>
<title>hello</title>
</show>
</channel>
</genre>
<genre type="blah2">
<channel name="Channel 3">
<show>
<title>hello</title>
</show>
</channel>
</genre>
</channels>
所以我的问题如下:
channelList = rootElem.find(".//channel[@name]")
howManyChannels = len(channelList)
for x in range(1, howManyChannels):
print x
print rootElem.find(".//channel[@name]["+str(x)+"]").get('name')
for y in rootElem.find(".//channel[@name]["+str(x)+"]"):
print y.findtext('title')
这会到达通道 2,然后出现以下错误:
Traceback (most recent call last):
File "parse.py", line 17, in <module>
print rootElem.find(".//channel[@name]["+str(x)+"]").get('name')
AttributeError: 'NoneType' object has no attribute 'get'
为什么没有代码:
for y in rootElem.find(".//channel[@name]["+str(x)+"]"):
包括第 3 个频道,为什么它像在另一个流派标签中一样被隔离?如何更改代码以适应这种情况?
我正在尝试将哪些频道与哪些节目一起存储在列表中。
更新: 我不明白为什么
channelList = rootElem.find(".//channel[@name][3]")
即使在循环之外也会产生错误。
url = 'myxmlurl.com/xml.xml'
request = urllib2.Request(url, headers={"Accept" : "application/xml"})
u = urllib2.urlopen(request)
tree = ElementTree.parse(u)
rootElem = tree.getroot()
【问题讨论】:
-
缩进很重要。如果您的代码没有正确缩进,我们无法评论它。
-
请将您的代码格式化为代码。
标签: python xml elementtree