我想对具有 namespace 但没有前缀的元素执行 iterfind()
。我想打电话
iterfind([tagname])
或 iterfind([tagname], [namespace dict])
懒得每次输入标签如下:
"{%s}tagname"% tree.nsmap[None]
详情
我正在运行来自 Google API 的 xml 响应。根节点定义了几个 namespace ,包括一个没有前缀的 namespace :xmlns="http://www.w3.org/2005/Atom"
看起来好像当我尝试搜索我的 etree 时,一切都像我对带有前缀的元素所期望的那样。例如:
>>> for x in root.iterfind('dxp:segment'): print x
...
<Element {http://schemas.google.com/analytics/2009}segment at 0x1211b98>
<Element {http://schemas.google.com/analytics/2009}segment at 0x1211d78>
<Element {http://schemas.google.com/analytics/2009}segment at 0x1211a08>
>>>
但是当我尝试搜索没有前缀的内容时,搜索不会自动为 root.nsmap[None]
添加命名空间。例如:
>>> for x in root.iterfind('entry'): print x
...
>>>
即使我尝试将 namespace 映射作为可选参数放入 iterfind
,它也不会附加 namespace 。
最佳答案
试试这个:
for x in root.iterfind('{http://www.w3.org/2005/Atom}entry'):
print x
更多信息:阅读文档:http://lxml.de/tutorial.html#namespaces
如果你不想输入它,并且你想提供一个命名空间映射,你总是必须使用一个前缀,例如:
nsmap = {'atom': 'http://www.w3.org/2005/Atom'}
for x in root.iterfind('atom:entry', namespaces=nsmap):
print x
(如果你想使用 xpath 也是一样)
文档中使用什么前缀(如果有的话)并不重要,重要的是您指定元素的完全限定名称,或者使用大括号表示法将其与 URI 一起完整写出,或者使用映射的前缀到一个 URI。
关于Python lxml iterfind 带命名空间但前缀=无,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6462061/