Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Adding xpath style parsing to weigh the options

  • Loading branch information...
commit 68165262ac40c1f4c60661540537f5ba52f373ca 1 parent db96b88
@abedra authored
View
6 test/Makefile
@@ -1,5 +1,11 @@
+all: xml xpath
+
xml:
gcc -o xml `xml2-config --cflags` xmlHandler.c `xml2-config --libs`
+xpath:
+ gcc -o xpath `xml2-config --cflags` xpathTest.c `xml2-config --libs`
+
clean:
rm xml
+ rm xpath
View
3  test/bad-sample.xml
@@ -0,0 +1,3 @@
+<badtag>
+ <something>something text</something>
+</badtag>
View
2  test/xmlHandler.c
@@ -64,7 +64,7 @@ int main(int argc, char **argv)
e = read(argv[1]);
printf("Got error from class %s with message %s\n", e->class, e->message);
- free(e);
+ if (e) free(e);
xmlCleanupParser();
xmlMemoryDump();
View
68 test/xpathTest.c
@@ -0,0 +1,68 @@
+#include <libxml/tree.h>
+#include <libxml/parser.h>
+#include <libxml/xpath.h>
+#include <libxml/xpathInternals.h>
+
+char *search(char *q, xmlDocPtr doc, xmlXPathContextPtr xpathCtx) {
+ xmlNodeSetPtr nodes;
+ xmlNodePtr cur;
+ xmlXPathObjectPtr xpathObj;
+
+ int i, size;
+ char *result;
+
+ xpathObj = xmlXPathEvalExpression(q, xpathCtx);
+ if (xpathObj == NULL) {
+ fprintf(stderr, "Error: unable to evaluate XPath expression\n");
+ xmlXPathFreeContext(xpathCtx);
+ xmlFreeDoc(doc);
+ return;
+ }
+
+ nodes = xpathObj->nodesetval;
+ size = (nodes) ? nodes->nodeNr : 0;
+
+ if (size == 1) {
+ printf("node %s\n", xmlNodeGetContent(nodes->nodeTab[0]));
+ } else {
+ for (i = 0; i < size; i++) {
+ cur = nodes->nodeTab[i];
+ printf("node %s\n", xmlNodeGetContent(cur));
+ }
+ }
+
+ xmlXPathFreeObject(xpathObj);
+ result = "";
+ return result;
+}
+
+int main(int argc, char **argv)
+{
+ xmlDocPtr doc;
+ xmlXPathContextPtr xpathCtx;
+
+ char *filename;
+
+ filename = argv[1];
+
+ doc = xmlParseFile(filename);
+ if (doc == NULL) {
+ fprintf(stderr, "Error: unable to parse file %s \n", filename);
+ return 1;
+ }
+
+ xpathCtx = xmlXPathNewContext(doc);
+ if (xpathCtx == NULL) {
+ fprintf(stderr, "Error: unable to create new XPath context\n");
+ xmlFreeDoc(doc);
+ return 1;
+ }
+
+ search("/notice/error/class", doc, xpathCtx);
+ search("/notice/error/message", doc, xpathCtx);
+
+ xmlXPathFreeContext(xpathCtx);
+ xmlFreeDoc(doc);
+
+ return 0;
+}
Please sign in to comment.
Something went wrong with that request. Please try again.