我支持使用Xerces-C进行XML解析的传统C++应用程序。我被.Net所宠坏,习惯于使用XPath从DOM树中选择节点。Xerces-C中的XPath支持
有没有办法在Xerces-C中访问某些有限的XPath功能?我正在寻找像selectNodes(“/ for/bar/baz”)。我可以手动执行此操作,但通过比较,XPath非常好。
我支持使用Xerces-C进行XML解析的传统C++应用程序。我被.Net所宠坏,习惯于使用XPath从DOM树中选择节点。Xerces-C中的XPath支持
有没有办法在Xerces-C中访问某些有限的XPath功能?我正在寻找像selectNodes(“/ for/bar/baz”)。我可以手动执行此操作,但通过比较,XPath非常好。
查看xerces faq。
http://xerces.apache.org/xerces-c/faq-other-2.html#faq-9
是否Xerces的-C++支持的XPath? No.Xerces-C++ 2.8.0和Xerces-C++ 3.0.1仅用于处理Schema标识约束的部分XPath实现。要获得完整的XPath支持,可以参考Apache Xalan C++或其他开源项目,如Pathan。
然而,使用xalan来做你想做的事情是相当容易的。
按照FAQ,的Xerces-C支持部分的XPath 1个实施:
相同的发动机通过DOM文档提供 ::评价API 让用户执行涉及一个DOMElement简单的XPath查询 只有节点 ,没有谓词测试,而 只允许“//”运算符作为 的初始步骤。
您使用DOMDocument::evaluate()来评估表达式,然后返回DOMXPathResult。
以下是XPath评估的一个工作示例,其中包含Xerces 3.1.2。
示例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库安装和C++文件名为xpath.cpp)
g++ -g -Wall -pedantic -L/opt/lib -I/opt/include -DMAIN_TEST xpath.cpp -o xpath -lxerces-c
./xpath
结果
hello world
有没有人使用这个功能?它有效吗?如果是这样,那么对于Xerces-C的哪些版本? – 2009-07-09 20:35:44