[英]Making lxml.objectify ignore xml namespaces?
所以我要处理一些看起来像这样的xml:
<ns2:foobarResponse xmlns:ns2="http://api.example.com">
<duration>206</duration>
<artist>
<tracks>...</tracks>
</artist>
</ns2:foobarResponse>
我找到了lxml和它的objectify模块,它允许你以pythonic方式遍历xml文档,就像字典一样。
问题是:每次尝试访问元素时都使用伪造的xml命名空间,如下所示:
from lxml import objectify
tree = objectify.fromstring(xml)
print tree.artist
# ERROR: no such child: {http://api.example.com}artist
它正在尝试使用父命名空间访问<artist>
,但标记不使用ns。
任何想法如何解决这个问题? 谢谢
根据lxml.objectify 文档 ,属性查找默认使用其父元素的命名空间。
你可能想要的工作是:
print tree["{}artist"]
如果你的孩子有一个非空的命名空间(例如“{ http:// foo / } artist”),这样的QName语法会起作用,但不幸的是,它看起来像当前的源代码将空命名空间视为没有命名空间,因此,所有objectify的查找优点将有助于用父命名空间替换空命名空间,并且你运气不好。
这可能是一个bug(“{}艺术家”应该工作),或者是为lxml人提交的增强请求。
目前,最好的办法可能是:
print tree.xpath("artist")
我不清楚你在这里使用xpath会有多大的性能影响,但这肯定有效。
仅供参考:请注意,从lxml 2.3开始,这可以正常工作。
从lxml更改日志:
“[...]
2.3(2011-02-06)增加了功能
- 在寻找孩子时,lxml.objectify将'{} tag'视为空命名空间,而不是父命名空间。
[...]”
在行动:
>>> xml = """<ns2:foobarResponse xmlns:ns2="http://api.example.com">
... <duration>206</duration>
... <artist>
... <tracks>...</tracks>
... </artist>
... </ns2:foobarResponse>"""
>>> tree = objectify.fromstring(xml)
>>> print tree['{}artist']
artist = None [ObjectifiedElement]
tracks = '...' [StringElement]
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.