XPath support in Xerces-C

I support an outdated C ++ application that uses Xerces-C for XML parsing. I messed up .Net and used to use XPath to select nodes from the DOM tree.

Is there a way to access the limited XPath features in Xerces-C? I am looking for something like selectNodes ("/ for / bar / baz"). I could do it manually, but XPath is so good at comparing.

+6
c ++ xpath xerces xerces-c
source share
3 answers

See faq xerces.

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

Does Xerces-C ++ support XPath? NoXerces-C ++ 2.8.0 and Xerces-C ++ 3.0.1 have a partial XPath implementation for the purpose of limiting restrictions on schema compliance. For full XPath support, you can refer to Apache Xalan C ++ or other open source projects such as Pathan.

It is quite easy to do what you want using xalan.

+4
source share

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

The same engine is available through DOMDocument :: evaluate the API so that the user can execute simple XPath queries with DOMElement nodes only, without predicate testing and allowing the "//" operator only as an initial step.

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

+1
source share

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

XML example

<?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 a standard installation of the xerces library and a C ++ file called xpath.cpp)

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

Result

 hello world 
+1
source share

All Articles