我支持使用XERCES-C进行XML解析的Legacy 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? No.Xerces-C ++ 2.8.0和Xerces-C ++ 3.0.1仅在处理模式身份约束的目的中具有部分XPATH实现。为了获得完整的XPATH支持,您可以引用Apache Xalan C ++或其他开源项目(如Pathan)。

但是,使用Xalan做您想做的事情很容易。

其他提示

这是一个有效的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支持部分XPATH 1实施:

通过DOMDOCUMENT :: RETURE API提供相同的引擎,使用户仅执行涉及Domelement节点的简单XPath查询,而没有谓词测试,并且仅允许“ //”操作员作为初始步骤。

你用 domdocument :: evaliate() 评估表达式,然后返回 DomxPathresult.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top