L'exemple http://xmlsoft.org/examples/xpath1.c(...) fait 250 lignes, oui, mais tu n'as peut-être pas besoin de tout cela. Déjà, si ton XML n'utilise pas de namespace, ça raccourcit de beaucoup.
Quelque chose minimaliste, qui parse t.xml et affiche les noeuds "matchant" l'expression xpath "//elem" pourrait ressembler à:
(il faut quand même y ajouter une petite gestion des erreurs)
#include <libxml/tree.h>
#include <libxml/xpath.h>
int main(int argc, char *argv[])
{
xmlDoc *doc;
xmlXPathContext *ctx;
xmlXPathObject *xpathObj;
xmlNode *node;
int i, n;
doc = xmlParseFile("t.xml");
ctx = xmlXPathNewContext(doc);
xpathObj = xmlXPathEvalExpression("//elem", ctx);
n = xpathObj->nodesetval->nodeNr;
for (i=0; i<n; i++) {
node = xpathObj->nodesetval->nodeTab[i];
printf("node: %s\n", node->name);
}
return 0;
}
Compile rapide avec gcc t.c -o t `pkg-config --cflags --libs libxml-2.0`
# exemple libxml2/xpath
Posté par Frédéric Péters (site web personnel) . En réponse au message code pour faire du xpath avec du xml en C. Évalué à 2.
#include <libxml/tree.h> #include <libxml/xpath.h> int main(int argc, char *argv[]) { xmlDoc *doc; xmlXPathContext *ctx; xmlXPathObject *xpathObj; xmlNode *node; int i, n; doc = xmlParseFile("t.xml"); ctx = xmlXPathNewContext(doc); xpathObj = xmlXPathEvalExpression("//elem", ctx); n = xpathObj->nodesetval->nodeNr; for (i=0; i<n; i++) { node = xpathObj->nodesetval->nodeTab[i]; printf("node: %s\n", node->name); } return 0; }Compile rapide avec gcc t.c -o t `pkg-config --cflags --libs libxml-2.0`