以下是使用Xerces 3.1.2进行 XPath 评估的工作示例。
XML 示例
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<ApplicationSettings>hello world</ApplicationSettings>
</root>
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
编译并运行(假设安装标准 xerces 库和名为xpath.cpp的 C++ 文件)
g++ -g -Wall -pedantic -L/opt/lib -I/opt/include -DMAIN_TEST xpath.cpp -o xpath -lxerces-c
./xpath
Run Code Online (Sandbox Code Playgroud)
结果
hello world
Run Code Online (Sandbox Code Playgroud)
见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仅为了处理模式身份约束而具有部分XPath实现.要获得完整的XPath支持,您可以参考Apache Xalan C++或Pathan等其他开源项目.
然而,使用xalan做你想做的事情相当容易.
| 归档时间: |
|
| 查看次数: |
7310 次 |
| 最近记录: |