4

我想知道是否可以在 libxml2 中使用相对 XPath 表达式。

这来自 javax.xml.xpath API,我想使用 libxml2 做类似的事情:

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

通过对元素的引用,现在可以编写相对 XPath 表达式来选择子元素:

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

2 回答 2

7

这是一些代码示例:

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>
}

希望这可以帮助某人。

于 2011-06-15T10:59:08.367 回答
5

设置 xmlXPathContext 对象的节点成员。

于 2010-05-16T15:30:20.107 回答