Python lxml iterfind w/命名空间但前缀=无
我想对具有命名空间但没有前缀的元素执行 iterfind()
。我想调用
iterfind([tagname])
或 iterfind([tagname], [namespace dict])
我不介意按如下方式输入标签: time:
"{%s}tagname" % tree.nsmap[None]
详细信息
我正在运行来自 Google API 的 xml 响应。根节点定义了多个命名空间,其中包括一个没有前缀的命名空间: 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
...
>>>
即使我尝试将名称空间映射作为 iterfind 的可选参数放入,它也不会附加名称空间。
I want to perform iterfind()
for elements which have a namespace but no prefix. I'd like to call
iterfind([tagname])
or iterfind([tagname], [namespace dict])
I don't care to enter the tag as follows every time:
"{%s}tagname" % tree.nsmap[None]
Details
I'm running through an xml response from a Google API. The root node defines several namespaces, including one for which there is no prefix: xmlns="http://www.w3.org/2005/Atom"
It looks as though when I try to search through my etree, everything behaves as I would expect for elements with a prefix. e.g.:
>>> 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>
>>>
But when I try to search for something without a prefix, the search doesn't automatically add the namespace for root.nsmap[None]
. e.g.:
>>> for x in root.iterfind('entry'): print x
...
>>>
Even if I try to throw the namespace map in as the optional argument for iterfind
, It won't attach the namespace.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
有关更多信息:阅读文档:http://lxml.de/tutorial.html#namespaces< /a>
如果您不想输入该内容,并且想要提供命名空间映射,则始终必须使用前缀,例如:(
如果您想使用 xpath,则同样的情况)
使用什么前缀该文件(如果有)并不重要,它是关于指定元素的完全限定名称,或者使用大括号表示法将其与 URI 一起写出,或者使用映射到 URI 的前缀。
Try this:
For more information: read the docs: http://lxml.de/tutorial.html#namespaces
If you do not want to type that, and you want to provide a namespace map, you always have to use a prefix, like this for example:
(same thing goes if you want to use xpath)
What prefix is used in the document, if any, is not important, it's about you specifying the fully qualified name of the element, either writing it out complete with URI using the curly bracket notation, or using a prefix that is mapped to a URI.
我发现您可以简单地添加一个映射到默认命名空间的空字符串(在 Python 3.9 中验证):
I found that you can simply add an empty string that maps to the default namespace (verified in Python 3.9):