XPath support in Xerces-C

2019-04-06 20:32发布

I am supporting a legacy C++ application which uses Xerces-C for XML parsing. I've been spoiled by .Net and am used to using XPath to select nodes from a DOM tree.

Is there any way to get access some limited XPath functionality in Xerces-C? I'm looking for something like selectNodes("/for/bar/baz"). I could do this manually, but XPath is so nice by comparison.

3条回答
Lonely孤独者°
2楼-- · 2019-04-06 21:07

Here is a working example of XPath evaluation with Xerces 3.1.2.

Sample 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;
}

Compile and run (assumes standard xerces library installation and C++ file named xpath.cpp)

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

Result

hello world
查看更多
贪生不怕死
3楼-- · 2019-04-06 21:22

According to the FAQ, Xerces-C supports partial XPath 1 implementation:

The same engine is made available through the DOMDocument::evaluate API to let the user perform simple XPath queries involving DOMElement nodes only, with no predicate testing and allowing the "//" operator only as the initial step.

You use DOMDocument::evaluate() to evaluate the expression, which then returns a DOMXPathResult.

查看更多
姐就是有狂的资本
4楼-- · 2019-04-06 21:23

See the xerces faq.

http://xerces.apache.org/xerces-c/faq-other-2.html#faq-9

Does Xerces-C++ support XPath? No.Xerces-C++ 2.8.0 and Xerces-C++ 3.0.1 only have partial XPath implementation for the purposes of handling Schema identity constraints. For full XPath support, you can refer Apache Xalan C++ or other Open Source Projects like Pathan.

It's fairly easy to do what you want using xalan however.

查看更多
登录 后发表回答