ElementTree 似乎无法在 findall() 结果上运行 findall()



我的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>

我有许多条目元素,每个元素都包含一个标题元素。我想查找哪个条目包含具有特定元素文本的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'元素。如果我查找:

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()返回对象的可能性是从它的输入不同的类,但是在任何一个对象上运行"类型"仅仅返回"实例"作为类型。ElementTree.

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

问题是代码中的document_node[0]已经引用了title元素,并且通过其子元素查找没有返回任何内容。

最新更新