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:
the xpathquery: //node/contentNodeTypeA is executed on the entire document.
Below you'll find the code that illustrates what I am trying to do.
Using libxml2 i do the following
code similar to what I am doing. When i try:
evaluator.setNewContext(node)
typeA = evaluator.xpathEval("//node/contentNodeTypeA")
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>
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")
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
Try to do the XPath expressions in more steps to see what do.
ASKER
@pepr the question was specific to libxml2
ASKER
@gertone - thanks that worked. It was silly of me. My Xpath was wrong.
welcome
The lxml module IS built around the libxml2 library and libxslt -- see http://lxml.de/
you will need ".//contentNodeTypeA" instead