Xerces-C中的XPath支持

Ada*_*gen 8 c++ xpath xerces xerces-c

我支持使用Xerces-C进行XML解析的遗留C++应用程序.我被.Net宠坏了,并习惯使用XPath从DOM树中选择节点.

有没有办法在Xerces-C中访问一些有限的XPath功能?我正在寻找像selectNodes("/ for/bar/baz")之类的东西.我可以手动执行此操作,但相比之下XPath非常好.

Mik*_*e S 6

以下是使用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)


Mat*_*att 5

见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做你想做的事情相当容易.