使lxml.objectify忽略xml名称空间?

ada*_*Lev 4 python xml lxml xml-namespaces

所以我要处理一些看起来像这样的xml:

<ns2:foobarResponse xmlns:ns2="http://api.example.com">
  <duration>206</duration>
  <artist>
    <tracks>...</tracks>
  </artist>
</ns2:foobarResponse>
Run Code Online (Sandbox Code Playgroud)

我找到了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
Run Code Online (Sandbox Code Playgroud)

它正在尝试使用<artist>父命名空间进行访问,但标记不使用ns.

任何想法如何解决这个问题?谢谢

Jef*_*ris 7

根据lxml.objectify 文档,属性查找默认使用其父元素的命名空间.

你可能想要的工作是:

print tree["{}artist"]
Run Code Online (Sandbox Code Playgroud)

如果你的孩子有一个非空的命名空间(例如"{ http:// foo / } artist"),这样的QName语法会起作用,但不幸的是,它看起来像当前的源代码将空命名空间视为没有命名空间,因此,所有objectify的查找优点将有助于用父命名空间替换空命名空间,并且你运气不好.

这可能是一个bug("{}艺术家"应该工作),或者是为lxml人提交的增强请求.

目前,最好的办法可能是:

print tree.xpath("artist")
Run Code Online (Sandbox Code Playgroud)

这是我不清楚多少表现打你会采取在这里使用XPath,但是这肯定的作品.