【问题标题】:ElementTree can't seem to run findall() on findall() resultsElementTree 似乎无法在 findall() 结果上运行 findall()
【发布时间】:2011-11-15 17:11:52
【问题描述】:

我的 XML 形状如下:

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:docs="http://schemas.google.com/docs/2007" xmlns:batch="http://schemas.google.com/gdata/batch"
    <entry gd:etag="&quot;HxYZGQVeHyt7ImBr&quot;">
        <title>Some document title I wish to find</title>

我有很多 entry 元素,每个元素都包含一个 title 元素。我希望找到哪个条目包含带有特定元素文本的标题元素。

我可以使用以下代码完美地遍历每个项目:

entry = './/{http://www.w3.org/2005/Atom}entry'  
document_nodes = document_feed_xml.findall(entry)
for document_node in document_nodes:
    logging.warn('entry item found!')
    logging.warn(pretty_print(document_node))
    logging.warn('-'*80)

这有效,返回:

WARNING:root:--------------------------------------------------------------------------------
WARNING:root:entry item found!
<ns0:entry ns1:etag="&quot;HxdWRh4MGit7ImBr&quot;" xmlns:ns0="http://www.w3.org/2005/Atom" xmlns:ns1="http://schemas.google.com/g/2005">
    <ns0:title>
        Some document title
    </ns0:title>
</ns0:entry>

所以现在我想在树的这个分支中寻找一个“标题”元素。如果我寻找:

title = './/{http://www.w3.org/2005/Atom}title'
title_nodes = document_node.findall(title)
for title_node in title_nodes:
    logging.warn('yaaay')
    logging.warn(title_node.text)
if not title_nodes:
    raise ValueError('Could not find any title elements in this entry')   

编辑:我最初通过一些调试获得了“document_node[0].findall”。删除它,上面的代码就可以工作了。这是错误的原因 - 感谢下面的绅士发现这个!

这会引发没有标题节点的错误。

这些结果看起来很奇怪,因为: - 我可以在文档中清楚地看到具有该名称空间的那个元素 - 我什至可以使用该命名空间直接为标题运行 findall(),然后查看结果

我想知道 findall() 返回与输入不同类的对象的可能性,但是在任一对象上运行 'type' 只会返回 'instance' 作为类型。 ElementTree 中有质量编程。

虽然 LXML 有更好的文档、更好的 xpath 支持和更好的代码,但由于技术原因,我不能使用 LXML,所以我不得不使用 ElementTree。

【问题讨论】:

  • FWIW,instance 类型仅仅意味着他们使用的是旧式类(新式类直到 2001 年 12 月的 Python 2.2 才引入)。这是因为 ElementTree 支持 Python 版本回到 1.5.2,所以它们不能使用新样式的类。
  • @kindall - 谢谢回复:旧式课程信息。

标签: python xpath elementtree


【解决方案1】:

问题是您的代码中的 document_node[0] 已经引用了 title 元素,并且查看其子元素不会返回任何内容。

【讨论】:

  • 我发誓我只在使用整个文档后才包含 [0] 不起作用。我已经删除了它,现在可以了。感谢您成为第二双眼睛!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
  • 2016-04-09
  • 1970-01-01
  • 2017-08-25
相关资源
最近更新 更多