我找不到很多使用xerces-c3.1评估XPath的例子。
给定以下示例XML输入:
<abc>
<def>AAA BBB CCC</def>
</abc>我需要通过XPath "/abc/def/text()“检索"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()它必须是一个节点集而不是我想要的确切节点吗?
我尝试了其他文本格式,比如“/abc/def/ XPath ()”和"DOMXPathResult::STRING_TYPE“。xerces总是抛出异常。
我做错什么了?
发布于 2013-01-08 02:08:46
我不使用Xerces C++编写代码,但它似乎实现了W3C DOM Level 3,因此我建议选择一个具有类似/abc/def的路径的元素节点,然后简单地访问result->getNodeValue()->getTextContent()来获取元素的内容(例如AAA BBB CCC)。
就我对DOM的理解而言,如果需要字符串值,则需要使用像string(/abc/def)这样的路径,然后使用result->getStringValue() (如果evaluate方法请求任何类型或STRING_TYPE作为结果类型)。
其他方法如果您知道自己只对文档顺序中的第一个节点感兴趣,那么可以用FIRST_ORDERED_NODE_TYPE计算/abc/def,然后访问result->getNodeValue()->getTextContent()。
https://stackoverflow.com/questions/14200623
复制相似问题