Making lxml.objectify ignore xml namespaces?

So, I have to deal with some xml that looks like this:

<ns2:foobarResponse xmlns:ns2="http://api.example.com">
  <duration>206</duration>
  <artist>
    <tracks>...</tracks>
  </artist>
</ns2:foobarResponse>

I found the lxml and objectify module, which allows you to move the XML document as a pythonic, for example, in a dictionary. <sh> The problem is that it uses a fake xml namespace every time you try to access an element, for example:

from lxml import objectify

tree = objectify.fromstring(xml)
print tree.artist
# ERROR: no such child: {http://api.example.com}artist

It tries to access <artist>with the parent namespace, but the tag does not use ns.

Any ideas how to get around this? Thanks

+3
source share
2 answers

lxml.objectify , .

, :

print tree["{}artist"]

QName, , , ( "{ http://foo/} artist", ), , , , , , .

( "{} artist" ), lxml.

:

print tree.xpath("artist")

, , xpath , , , .

+7

: , , 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]
>>>
+3

Source: https://habr.com/ru/post/1751425/


All Articles