我的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=""HxYZGQVeHyt7ImBr"">
<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=""HxdWRh4MGit7ImBr"" 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.findall”。除去这个,上面的代码就能工作了。这就是错误的原因--感谢下面的长官发现了这个!!
这会引发没有标题节点的错误。
这些结果似乎很奇怪,因为:-我可以在文档中清楚地看到带有名称空间的元素--我甚至可以使用名称空间直接为title运行findall(),并查看结果。
我想知道findall()返回与其输入不同类的对象的可能性,但是在任何一个对象上运行' type‘只是返回’实例‘作为类型。质量编程在那里,ElementTree。
虽然LXML有更好的文档、更好的xpath支持和更好的代码,但由于技术原因,我不能使用,所以我不得不使用ElementTree。
发布于 2011-11-15 17:29:10
问题是,代码中的document_node[0]已经引用了title元素,而查看它的子元素却什么也不返回。
https://stackoverflow.com/questions/8140284
复制相似问题