我正在支持一个使用Xerces-C进行C++解析的遗留C++应用程序。我被.Net宠坏了,习惯于使用XPath从DOM树中选择节点。
有没有办法访问Xerces-C中的一些有限的XPath功能?我正在寻找类似于selectNodes("/ for /bar/baz")的东西。我可以手动完成此操作,但与之相比,XPath更好。
发布于 2009-07-09 23:59:41
请参阅xerces常见问题解答。
http://xerces.apache.org/xerces-c/faq-other-2.html#faq-9
Xerces-C++支持XPath吗? and。Xerces-C++ 2.8.0和Xerces-C++ 3.0.1只有部分XPath实现来处理模式标识约束。要获得完整的XPath支持,您可以参考Apache Xalan C++或其他开源项目,如Pathan。
但是,使用xalan可以很容易地完成您想要的操作。
发布于 2015-10-15 02:20:48
下面是一个使用Xerces 3.1.2进行XPath评估的工作示例。
示例XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<ApplicationSettings>hello world</ApplicationSettings>
</root>C++
#include <iostream>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/util/TransService.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
using namespace xercesc;
using namespace std;
int main()
{
XMLPlatformUtils::Initialize();
// create the DOM parser
XercesDOMParser *parser = new XercesDOMParser;
parser->setValidationScheme(XercesDOMParser::Val_Never);
parser->parse("sample.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("/root/ApplicationSettings"),
root,
NULL,
DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE,
NULL);
if (result->getNodeValue() == NULL)
{
cout << "There is no result for the provided XPath " << endl;
}
else
{
cout<<TranscodeToStr(result->getNodeValue()->getFirstChild()->getNodeValue(),"ascii").str()<<endl;
}
XMLPlatformUtils::Terminate();
return 0;
}编译并运行(假定标准的xerces库安装和名为xpath.cpp的C++文件)
g++ -g -Wall -pedantic -L/opt/lib -I/opt/include -DMAIN_TEST xpath.cpp -o xpath -lxerces-c
./xpath结果
hello world发布于 2009-07-09 19:59:03
根据FAQ的说法,Xerces-C支持部分XPath 1实现:
通过DOMDocument::evaluate API提供相同的引擎,让用户只执行涉及DOMElement节点的简单XPath查询,而不进行谓词测试,并且只允许"//“运算符作为初始步骤。
使用DOMDocument::evaluate()计算表达式的值,然后返回一个DOMXPathResult。
https://stackoverflow.com/questions/1106065
复制相似问题