Skip to content

Instantly share code, notes, and snippets.

@mygnu
Created January 27, 2014 01:22
Show Gist options
  • Save mygnu/8641855 to your computer and use it in GitHub Desktop.
Save mygnu/8641855 to your computer and use it in GitHub Desktop.
libxml2 test
/* Code: */
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <stdio.h>
xmlDocPtr
getdoc (char *docname)
{
xmlDocPtr doc;
doc = xmlParseFile(docname);
if (doc == NULL ) {
fprintf(stderr,"Document not parsed successfully. \n");
return NULL;
}
return doc;
}
xmlXPathObjectPtr
getnodeset (xmlDocPtr doc, xmlChar *xpath)
{
xmlXPathContextPtr context;
xmlXPathObjectPtr result;
context = xmlXPathNewContext(doc); /* initialize the context */
if (context == NULL) /* test if null */
{
printf("Error in xmlXPathNewContext\n");
return NULL;
}
result = xmlXPathEvalExpression(xpath, context); /* evaluates XPath location
in the given context */
xmlXPathFreeContext(context); /* free the context memory */
if (result == NULL)
{
printf("Error in xmlXPathEvalExpression\n");
return NULL;
}
if(xmlXPathNodeSetIsEmpty(result->nodesetval))
{
xmlXPathFreeObject(result);
printf("No result\n");
return NULL;
}
return result;
}
int
main(int argc, char **argv)
{
char *docname = "nodehistory.xml";
xmlDocPtr doc;
xmlChar *xpath = (xmlChar*) argv[1];
xmlNodeSetPtr nodeset;
xmlXPathObjectPtr result;
int i;
xmlChar *keyword;
if (argc <= 1)
{
printf("Usage: %s keyword\n", argv[0]);
return(0);
}
doc = getdoc(docname);
result = getnodeset (doc, xpath);
if (result) /* if not NULL */
{
double total = 0;
nodeset = result->nodesetval;
for (i=0; i < nodeset->nodeNr; i++)
{
keyword = xmlNodeListGetString
(doc, nodeset->nodeTab[i]->xmlChildrenNode, 1);
printf("content of the element: %s\n", keyword);
total = total + (atof((char *)keyword)/1000000);
xmlFree(keyword);
}
xmlXPathFreeObject (result);
printf("total megabytes used %f mb\n", total); /* sould be able to return this value to another function */
}
xmlFreeDoc(doc);
xmlCleanupParser();
return (1);
}
/* main.c ends here */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment