【发布时间】:2017-02-19 22:41:13
【问题描述】:
我需要处理一个包含许多这样结构的节点的大文件
<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
程序崩溃并显示他的错误消息 AttributeError: 'NoneType' 对象没有属性 'text'
谁能帮忙?
【问题讨论】:
-
在尝试访问
text属性之前,必须检查对象是否为None。 -
我不确定,但我发现了一个区别 - 在新版本中,您在路径中使用
./而不是name。 -
非常感谢 dopstar
标签: python xml-parsing lxml elementtree