1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| #include <string.h>
#include <sstream>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <iostream>
using namespace std;
void xpathParsing(xmlXPathContext xpathCtx){
string Xpth("//");
Xpth.append("*[contains(name(),'toto')]"); //the // allow to select all descendants of the root node
xmlXPathObjectPtr xpathObject;
xmlNodeSetPtr n;
xmlNodePtr propsNode;
xpathObject = xmlXPathEvalExpression((const xmlChar*)Xpth.data(), xpathCtx);
if(xpathObject == NULL) {
string err("Error: unable to evaluate xpath expression \n");
throw (err);
}
if(!xmlXPathNodeSetIsEmpty(xpathObject->nodesetval)){
n=xpathObject->nodesetval;
for (int i=0; i < n->nodeNr; i++) {
cout << n->nodeTab[i]->name << endl;
if(n->nodeTab[i]->properties == NULL){
cout << "NO PROPS" << endl;
}else{
for (propsNode = n->nodeTab[i]; propsNode->properties != NULL; propsNode->properties = n->nodeTab[i]->properties->next) {
cout << "+" <<propsNode->properties->name << endl;
}
}
if(n->nodeTab[i]->xmlChildrenNode == NULL){
cout << "NO CHILD" << endl;
}else{
while (n->nodeTab[i]->xmlChildrenNode != NULL) {
if((n->nodeTab[i]->xmlChildrenNode->type == XML_ELEMENT_NODE)){
cout << "-" << n->nodeTab[i]->xmlChildrenNode->name << endl;
}
n->nodeTab[i]->xmlChildrenNode = n->nodeTab[i]->xmlChildrenNode->next;
}
}
}
}else{
cout << "empty" << endl;
}
xmlXPathFreeObject(xpathObject);
}
int main(int argc, char **argv) {
xmlDocPtr doc;
xmlXPathContext xpathCtx;
xmlInitParser();
xmlXPathInit();
xmlKeepBlanksDefault(0);
doc = xmlReadFile("TestFESA210.xml",NULL, 0);
if (doc == NULL) {
string err("Invalid XML document\n");
throw (err);
}
xpathCtx = xmlXPathNewContext(doc);
if(xpathCtx == NULL) {
string err("Error: unable to create new XPath context\n");
throw (err);
}
cout << "PREMIER XPATH" << endl;
xpathParsing(xpathCtx);
cout << endl << "SECOND XPATH" << endl;
xpathParsing(xpathCtx);
xmlXPathFreeContext(xpathCtx);
xmlFreeDoc(doc);
xmlCleanupParser();
xmlMemoryDump();
return (1);
} |
Partager