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 85 86 87 88
| #include <stdlib.h>
#include <stdio.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
/*
gcc -Wall `xml2-config --cflags` `xml2-config --libs` node_dump.c -o node_dump
<?xml version="1.0" encoding="ISO-8859-1" ?>
<exemple>
<identifiant name="Nicko">
<message index="1">
<contenu>Ceci est un test de Nicko</contenu>
<heure>22:07:37</heure>
<date>12.04.2010</date>
</message>
<message index="10">
<contenu>Ceci est un second test de Nicko</contenu>
<heure>22:17:37</heure>
<date>13.04.2010</date>
</message>
</identifiant>
<identifiant name="Micko">
<message index="3">
<contenu>Ceci est un test de Micko</contenu>
<heure>22:07:37</heure>
<date>12.04.2010</date>
</message>
<message index="1">
<contenu>Ceci est un second test de Micko</contenu>
<heure>22:17:37</heure>
<date>13.04.2010</date>
</message>
</identifiant>
</exemple>
*/
int main(int argc, char **argv) {
xmlDocPtr doc;
xmlXPathContextPtr ctxt;
xmlXPathObjectPtr xpathRes;
if (2 != argc) {
fprintf(stderr, "usage: %s [FICHIER À PARSER]\n", argv[0]);
return EXIT_FAILURE;
}
if (NULL == (doc = xmlParseFile(argv[1]))) {
fprintf(stderr, "Échec de xmlParseFile()\n");
return EXIT_FAILURE;
}
xmlXPathInit();
if (NULL == (ctxt = xmlXPathNewContext(doc))) {
fprintf(stderr, "Erreur lors de la création du contexte XPath\n");
return EXIT_FAILURE;
}
if (NULL == (xpathRes = xmlXPathEvalExpression(BAD_CAST "//message[@index = '1']", ctxt))) {
fprintf(stderr, "Erreur sur l'expression XPath\n");
return EXIT_FAILURE;
}
if (XPATH_NODESET == xpathRes->type) {
int i;
xmlBufferPtr buf;
if (NULL == (buf = xmlBufferCreate())) {
fprintf(stderr, "Échec création du buffer\n");
return EXIT_FAILURE;
}
if (0 == xpathRes->nodesetval->nodeNr) {
printf("Aucune correspondance\n");
} else {
for (i = 0; i < xpathRes->nodesetval->nodeNr; i++) {
const xmlChar *content;
xmlNodePtr n = xpathRes->nodesetval->nodeTab[i];
xmlBufferEmpty(buf);
xmlNodeDump(buf, doc, n, 0 /* Niveau de démarrage de l'indentation */, 1 /* 0 pour aucun formatage */);
content = xmlBufferContent(buf);
printf("Contenu trouvé : %s\n", content);
}
xmlBufferFree(buf);
}
}
xmlXPathFreeObject(xpathRes);
xmlXPathFreeContext(ctxt);
xmlFreeDoc(doc);
return EXIT_SUCCESS;
} |
Partager