• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 612
  • Last Modified:

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

0
geldfeld
Asked:
geldfeld
  • 3
  • 2
  • 2
1 Solution
 
Geert BormansCommented:
'//foo' always starts from the document node
try
'.//foo' instead, '.' being the context node
0
 
Geert BormansCommented:
note that you will not find ".//node/contentNodeTypeA" since you are allready in the context of "node"
you will need ".//contentNodeTypeA" instead
0
 
peprCommented:
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.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
geldfeldAuthor Commented:
@pepr  the question was specific to libxml2

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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now