我支持使用 Xerces-C 进行 XML 解析的旧版 C++ 应用程序。我被 .Net 宠坏了,并且习惯于使用 XPath 从 DOM 树中选择节点。
有什么方法可以访问 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 实现,用于处理 Schema 标识约束。要获得完整的 XPath 支持,您可以参考 Apache Xalan C++ 或其他开源项目,例如 Pathan。
然而,使用 xalan 做你想做的事情是相当容易的。
这是使用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
根据FAQ,Xerces-C 支持部分 XPath 1 实现:
通过 DOMDocument::evaluate API 可以使用相同的引擎,让用户执行仅涉及 DOMElement 节点的简单 XPath 查询,无需谓词测试,并且仅允许“//”运算符作为初始步骤。
您使用DOMDocument::evaluate()来评估表达式,然后返回DOMXPathResult。