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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With