我正在支持一个使用Xerces-C进行XML解析的传统C++应用程序。 我已经习惯了使用XPath从DOM树中选择节点,并且被.Net宠坏了。
有没有办法在Xerces-C中获取一些有限的XPath功能? 我正在寻找类似于selectNodes(“/ for / bar / baz”)之类的东西。 虽然可以手动完成此操作,但与XPath相比,它并不理想。
查看xerces常见问题解答。
http://xerces.apache.org/xerces-c/faq-other-2.html#faq-9
Xerces-C++是否支持XPath?不支持。Xerces-C++ 2.8.0和Xerces-C++ 3.0.1只有部分XPath实现,用于处理模式标识约束。要获得完整的XPath支持,您可以参考Apache Xalan C++或其他开源项目,如Pathan。<?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库已安装并且C++文件命名为xpath.cpp)
g++ -g -Wall -pedantic -L/opt/lib -I/opt/include -DMAIN_TEST xpath.cpp -o xpath -lxerces-c
./xpath
结果
hello world
您可以使用DOMDocument::evaluate()来评估表达式,然后返回DOMXPathResult。相同的引擎可以通过DOMDocument::evaluate API 使用,让用户执行涉及DOMElement节点的简单XPath查询,但不能进行断言测试,而且只允许以“//”操作符作为初始步骤。