Can I use relative XPath expressions in libxml2?

I am wondering if relative XPath expressions can be used in libxml2.

This is from the javax.xml.xpath API, and I would like to do something like this with libxml2:

Node widgetNode = (Node) xpath.evaluate(expression, document, XPathConstants.NODE); 

With reference to an element, a relative XPath expression can now be written to select a child element:

 XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "manufacturer"; Node manufacturerNode = (Node) xpath.evaluate(expression, **widgetNode**, XPathConstants.NODE); 
+4
source share
2 answers

Set the node member of the xmlXPathContext object.

+5
source

Here is a sample code:

 xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc); const xmlChar* xpathExpr = BAD_CAST "//column"; xmlXPathObjectPtr columnXPathObj = xmlXPathEvalExpression(xpathExpr, xpathCtx); // Do whatever you want with your query here. Usually iterate over the result. // Inside this iteration I do: cur = columnNodes->nodeTab[i]; // Important part xpathCtx->node = cur; // After which you can do something like: xmlXPathObjectPtr screenXPathObj = xmlXPathEvalExpression(BAD_CAST "screen", xpathCtx); xmlNodeSetPtr screenNodes = screenXPathObj->nodesetval; for (int j = 0; j < screenNodes->nodeNr; j++) { // You're now iterating over the <screen>s inside the curent <column> } 

Hope this helps someone.

+6
source

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


All Articles