Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use relative XPath expressions in libxml2?

Tags:

c

xpath

libxml2

I am wondering whether it is possible to use relative XPath expressions in libxml2.

This is from the javax.xml.xpath API and I would like to do the similar thing using libxml2:

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

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

XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "manufacturer";
Node manufacturerNode = (Node) xpath.evaluate(expression, **widgetNode**, XPathConstants.NODE);
like image 869
brbr Avatar asked Dec 18 '22 00:12

brbr


1 Answers

Here is some code example:

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.

like image 76
Tudor Avatar answered Dec 28 '22 06:12

Tudor