我在解析特定类型的XML时遇到困难。用Python解析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'
为什么没有按't代码:
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()
缩进问题。如果您的代码没有正确缩进,我们无法对您的代码发表评论。 – Marcin
请将代码格式化为代码。 – Marcin