首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >尝试遍历XML :无法获取子节点的值

尝试遍历XML :无法获取子节点的值
EN

Stack Overflow用户
提问于 2016-10-11 19:38:24
回答 1查看 58关注 0票数 2

我需要处理一个包含许多节点的大型文件,如下所示

代码语言:javascript
复制
<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。运行时

代码语言:javascript
复制
for elem in tree.iterfind('{http://www.cc.com/a}category'):
    requestedName = elem.find('{http://www.cc.com/a}name').text
    print requestedName

它工作正常

运行时

代码语言:javascript
复制
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个请求值

代码语言:javascript
复制
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‘

谁能帮上忙?

EN

回答 1

Stack Overflow用户

发布于 2016-10-12 01:07:15

你说得对,多普斯塔!非常感谢

代码语言:javascript
复制
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.text
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39976405

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档