【问题标题】:Trying to iterate through XML : can't get subnode's values尝试遍历 XML:无法获取子节点的值
【发布时间】: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


【解决方案1】:

你是对的 Dopstar !非常感谢

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 2020-02-25
    相关资源
    最近更新 更多