Link to home
Start Free TrialLog in
Avatar of geldfeld
geldfeld

asked on

How to perform Xpath queries on Children Nodes ( using libxml2 )

I want to perform Xpath queries in the context of a chld node and not the document. Below I have
code similar to what I am doing. When i try:

      evaluator.setNewContext(node)
      typeA = evaluator.xpathEval("//node/contentNodeTypeA")

Open in new window


the xpathquery: //node/contentNodeTypeA  is executed on the entire document.

Below you'll find the code that illustrates what I am trying to do.

<rootNode>
     <nodes>
               <node>    <contentNodeTypeA/><contentNodeTypeB/>   </node>
               <node>     <contentNodeTypeA/><contentNodeTypeB/>   </node>
               <node>     <contentNodeTypeA/><contentNodeTypeB/>    </node>
      </nodes>
</rootNode>

Open in new window


Using libxml2 i do the following
import libxml2

doc = libxml2.parseFile ("doc.xml")
evaluator = doc.xpathNewContext()

nodeList  = evaluator.xpathEval("//rootNode/nodes/node")

for node in nodeList:
      evaluator.setNewContext(node)
      typeA = evaluator.xpathEval("//node/contentNodeTypeA")
      typeB = evaluator.xpathEval("//node/contentNodeTypeA")
      

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Gertone (Geert Bormans)
Gertone (Geert Bormans)
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
note that you will not find ".//node/contentNodeTypeA" since you are allready in the context of "node"
you will need ".//contentNodeTypeA" instead
Avatar of pepr
pepr

Have a look at Chapter 12 in "Dive Into Python 3" by Mark Pilgrim (http://diveintopython3.org/xml.html) namely the 12.6. Going Further With lxml (http://diveintopython3.org/xml.html#xml-lxml) for some details.

Try to do the XPath expressions in more steps to see what do.
Avatar of geldfeld

ASKER

@pepr  the question was specific to libxml2

@gertone - thanks that worked. It was silly of me. My Xpath was wrong.
The lxml module IS built around the libxml2 library and libxslt -- see http://lxml.de/