我想知道是否可以在 libxml2 中使用相对 XPath 表达式。
这是来自 javax.xml.xpath API,我想使用 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);
最佳答案
下面是一些代码示例:
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>
}
希望这对某人有帮助。
关于我可以在 libxml2 中使用相对 XPath 表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2828358/