Xerces-C中的XPath支持

12

我正在支持一个使用Xerces-C进行XML解析的传统C++应用程序。 我已经习惯了使用XPath从DOM树中选择节点,并且被.Net宠坏了。

有没有办法在Xerces-C中获取一些有限的XPath功能? 我正在寻找类似于selectNodes(“/ for / bar / baz”)之类的东西。 虽然可以手动完成此操作,但与XPath相比,它并不理想。

3个回答

7

查看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实现,用于处理模式标识约束。要获得完整的XPath支持,您可以参考Apache Xalan C++或其他开源项目,如Pathan。
使用xalan很容易实现您想要的功能。

6
以下是使用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库已安装并且C++文件命名为xpath.cpp

g++ -g -Wall -pedantic -L/opt/lib -I/opt/include -DMAIN_TEST xpath.cpp -o xpath -lxerces-c
./xpath

结果

hello world

尝试将查询更改为以下内容:count(//somenode/subnode/[@someattribute='somevalue'])它会抛出一个DOMXPathException异常。 - pfa

2
根据常见问题解答,Xerces-C支持部分XPath 1实现:

相同的引擎可以通过DOMDocument::evaluate API 使用,让用户执行涉及DOMElement节点的简单XPath查询,但不能进行断言测试,而且只允许以“//”操作符作为初始步骤。

您可以使用DOMDocument::evaluate()来评估表达式,然后返回DOMXPathResult

有人使用过这个功能吗?它有效吗?如果有效,是哪些版本的Xerces-C? - Adam Tegen
@AdamTegen 是的,我知道已经过去6年了,但Xerces仍然很受欢迎。我提供了一个使用Xerces 3.1.2实现XPath评估的示例。 - Mike S

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接