【问题标题】:Parsing XML with Python ignoring parts使用 Python 解析 XML 忽略部分
【发布时间】: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


【解决方案1】:

首先,您发布的代码在语法上无效,因为它没有缩进。但是,问题的根源在于您正在使用range 进行迭代。

代替:

channelList = rootElem.find(".//channel[@name]")
howManyChannels = len(channelList)


for x in range(1, howManyChannels):

做:

channelList = rootElem.find(".//channel[@name]")
for channel in channelList:
    pass #whatever

这样,您无需再次搜索频道。

此外,您的搜索“不起作用”,因为没有名称为 "3" 的频道元素。尝试搜索"Channel 3"

【讨论】:

  • 好的,但是将代码更改为上面的代码不会允许以下代码 print rootElem.find(".//channel[@name]["+str(x)+"]").get('name') 工作,因为 x 必须是数字而不是对象。很抱歉出现缩进错误,这是我在最初的帖子中的错,代码没有这样反映。
  • @JavaWizKid 你没有通读这篇文章吗?您无需再次搜索该频道,因为它就在那里。
  • 好的,感谢您的循环修复。这并不能解决问题,如果我只是在循环之外使用 channelList = rootElem.find(".//channel[@name][3]") 并打印它会给出错误。
猜你喜欢
  • 1970-01-01
  • 2011-01-09
  • 2019-06-09
  • 2023-03-22
  • 2020-09-19
  • 1970-01-01
  • 2011-05-02
  • 2019-02-06
  • 1970-01-01
相关资源
最近更新 更多