Python libxml2 XPath / Namespace help

I am trying to learn how to make XPath requests from Python using this example XML file: http://pastie.org/1333021 I just added a namespace for this because my application uses it.

Basically, I want to execute a top-level query that returns a subset of nodes and then requests a subset (on a much larger scale than this example)

So, this is my code to first find all the nodes <food>and then iterate over the description of each of them.

#!/usr/bin/python2

import libxml2

doc = libxml2.parseFile("simple.xml")
context = doc.xpathNewContext()

context.xpathRegisterNs("db", "http://examplenamespace.com")
res = context.xpathEval("//db:food")

for node in res:
    # Query xmlNode here
    print "Got Food Node:"
    desc = node.xpathEval('db:description') # this is wrong?
    print desc

So this is a namespace problem, if I remove an attribute xlnsfrom an XML file and use only basic XPATH queries without db:, it works fine. The top query //db:foodworks fine, but the second cannot be evaluated.

, - /.

+3
1

libxml2, lxml.etree.

. xpathEval node , -, .

reset , :

>>> import libxml2
>>> from urllib2 import urlopen
>>> data = urlopen('http://pastie.org/pastes/1333021/download').read()
>>>
>>> doc = libxml2.parseMemory(data,len(data))
>>>
>>> context = doc.xpathNewContext()
>>> context.xpathRegisterNs("db", "http://examplenamespace.com")
0
>>>
>>> for res in context.xpathEval("//db:food"):
...     context.setContextNode(res)
...     print "Got Food Node:"
...     desc = context.xpathEval('./db:description')[0]
...     print desc
...
Got Food Node:
<description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
Got Food Node:
<description>light Belgian waffles covered with strawberries and whipped cream</description>
Got Food Node:
<description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
Got Food Node:
<description>thick slices made from our homemade sourdough bread</description>
Got Food Node:
<description>two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
+5

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


All Articles