【发布时间】:2010-11-09 12:22:19
【问题描述】:
我支持使用 Xerces-C 进行 XML 解析的旧版 C++ 应用程序。我被 .Net 宠坏了,习惯使用 XPath 从 DOM 树中选择节点。
有什么方法可以访问 Xerces-C 中一些有限的 XPath 功能?我正在寻找类似 selectNodes("/for/bar/baz") 的东西。我可以手动执行此操作,但相比之下 XPath 非常好。
【问题讨论】:
我支持使用 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 让用户执行简单的 XPath 涉及 DOMElement 节点的查询 只有,没有谓词测试和 仅允许“//”运算符作为 第一步。
您使用DOMDocument::evaluate() 计算表达式,然后返回DOMXPathResult。
【讨论】: