我需要处理一个包含许多节点的大型文件,如下所示
<category name="28931778o.rjpf">
<name>RequestedName</name>
<root>0</root>
<online>1</online>
<description xml:lang="pt-PT">mydescription </description>
<category-links/>
<template/>
<parent name="PTW-0092"/>
<custom-attributes>
<custom-attribute name="sortkey" dt:dt="string">RequestedValue</custom-attribute>
<custom-attribute name="ShortLink" dt:dt="string" xml:lang="pt-PT">/Requested_Url.html</custom-attribute>
<custom-attribute name="ShortLinkActivate" dt:dt="string" xml:lang="pt-PT">true</custom-attribute>
...
</category>我需要为每个类别取回3个请求值。我使用Python、.27和etree。运行时
for elem in tree.iterfind('{http://www.cc.com/a}category'):
requestedName = elem.find('{http://www.cc.com/a}name').text
print requestedName它工作正常
运行时
for elem in tree.iterfind('{http://www.cc.com/a}category/{http://www.cc.com/a}custom-attributes/{http://www.cc.com/a}custom-attribute[@name="sortkey"]'):
print elem.text当我想要检索所有三个值时,它工作得很好,但问题来了。我尝试查找一个“类别”节点,并在其中查找2个请求值
for elem in tree.iterfind('{http://www.cc.com/a}category'):
requestedName = elem.find('{http://www.cc.com/a}name').text
print requestedName
Requestedsortkey = elem.find('./{http://www.cc.com/a}custom-attributes/{http://www.cc.com/a}custom-attribute[@name="sortkey"]')
print Requestedsortkey.text
RequestedUrl = elem.find('./{http://www.cc.com/a}custom-attributes/{http://www.cc.com/a}custom-attribute[@name="ShortLink"]')
print RequestedUrl.text程序崩溃并显示错误消息文本:'NoneType‘对象没有属性’AttributeError‘
谁能帮上忙?
发布于 2016-10-12 01:07:15
你说得对,多普斯塔!非常感谢
for elem in tree.iterfind('{http://www.cc.com/a}category'):
requestedName = elem.find('{http://www.cc.com/a}name').text
print requestedName
Requestedsortkey = elem.find('{http://www.cc.com/a}custom-attributes/{http://www.cc.com/a}custom-attribute[@name="sortkey"]')
if Requestedsortkey <> None:
print Requestedsortkey.text
RequestedUrl = elem.find('{http://www.cc.com/a}custom-attributes/{http://www.cc.com/a}custom-attribute[@name="ShortLink"]')
if RequestedUrl <> None :
print RequestedUrl.texthttps://stackoverflow.com/questions/39976405
复制相似问题