Xerces-c 3.1 XPath评估

3

我没有找到使用xerces-c 3.1评估XPath的很多示例。

给定以下示例XML输入:

<abc> 
    <def>AAA BBB CCC</def>
</abc>

我需要通过XPath "/abc/def/text()[0]"检索出"AAA BBB CCC"字符串。

以下代码可以正常工作:

XMLPlatformUtils::Initialize();
// create the DOM parser
XercesDOMParser *parser = new XercesDOMParser;
parser->setValidationScheme(XercesDOMParser::Val_Never);
parser->parse("test.xml");
// get the DOM representation
DOMDocument *doc = parser->getDocument();
// get the root element
DOMElement* root = doc->getDocumentElement();

// evaluate the xpath
DOMXPathResult* result=doc->evaluate(
    XMLString::transcode("/abc/def"), // "/abc/def/text()[0]"
    root,
    NULL,
    DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE, //DOMXPathResult::ANY_UNORDERED_NODE_TYPE, //DOMXPathResult::STRING_TYPE,
    NULL);

// look into the xpart evaluate result
result->snapshotItem(0);
std::cout<<StrX(result->getNodeValue()->getFirstChild()->getNodeValue())<<std::endl;;

XMLPlatformUtils::Terminate();
return 0;

但是我真的很讨厌那个:

result->getNodeValue()->getFirstChild()->getNodeValue()

我需要一个节点集而不是我想要的确切节点吗?

我尝试了其他格式的XPath,例如“/abc/def/text()[0]”和“DOMXPathResult :: STRING_TYPE”。 xerces总是抛出异常。

我做错了什么?

1个回答

4
我不使用Xerces C++,但它似乎实现了W3C DOM Level 3,基于此我建议使用像/abc/def这样的路径选择一个元素节点,然后简单地访问result->getNodeValue()->getTextContent()来获取元素的内容(例如AAA BBB CCC)。
就我所了解的DOM API,如果您想要一个字符串值,那么您需要使用像string(/abc/def)这样的路径,然后result->getStringValue()应该可以实现(如果evaluate方法请求任何类型或STRING_TYPE作为结果类型)。
如果您知道您只对文档顺序中的第一个节点感兴趣,则可以使用FIRST_ORDERED_NODE_TYPE评估/abc/def,然后访问result->getNodeValue()->getTextContent()

1
无论传递什么类型到evaluate()中,result->getStringValue()总是抛出异常。而result->getNodeValue()->getTextContent()可以正常工作。谢谢。 - John Crane
有一个XPath可以使result->getStringValue()正常工作将是非常好的。有人知道怎么做吗? - John Crane
@JohnCrane 有没有办法知道一个文档是否由解析器拥有? 你能否看一下这个问题.. http://stackoverflow.com/questions/23673300/how-to-know-if-a-domdocument-is-created-using-a-parser - Pavan Dittakavi
Xerces不支持字符串返回类型的XPath:https://github.com/apache/xerces-c/blob/4bac3c53e44506591c2892cc19f0452be169b401/src/xercesc/dom/impl/DOMXPathExpressionImpl.cpp#L119 - Chronial

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接