/* Code: */ #include "xmlparsing.h" #include <libxml/parser.h> #include <libxml/xpath.h> #include <stdio.h> #include <string.h> static xmlDocPtr getdoc (const char *filename); static xmlXPathObjectPtr getnodeset (xmlDocPtr docPtr, xmlChar *xpath); /* takes two pointers to string as name of the document and element */ char * getElementContent(char * filename, char * elementname) { char element[50] = "//"; /* needs // prefix for some reason */ strcat(element, elementname); xmlDocPtr doc = getdoc(filename); /* xmlDocPtr to the document */ xmlChar *xpath = (xmlChar*) element; /* is the name of the element */ xmlXPathObjectPtr result = getnodeset (doc, xpath); xmlNodeSetPtr nodeset; int i; xmlChar *keyword = (xmlChar *) malloc(sizeof(char) * 50); // not sure how to do this properly if (result) /* if not NULL */ { nodeset = result->nodesetval; for (i=0; i < nodeset->nodeNr; i++) { keyword = xmlNodeListGetString (doc, nodeset->nodeTab[i]->xmlChildrenNode, 1); return (char *)keyword; xmlFree(keyword); } xmlXPathFreeObject (result); } xmlFreeDoc(doc); xmlCleanupParser(); return NULL; } /* takes pointer to a string of the name of the document */ static xmlDocPtr getdoc (const char *filename) { xmlDocPtr docPtr; docPtr = xmlParseFile(filename); if (docPtr == NULL ) { fprintf(stderr,"Document not parsed successfully. \n"); return NULL; } return docPtr; } /* takes a xmlDocPtr to the xml document and a xmlChar string pointer as an element name */ static 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("There is no element of this name \n"); return NULL; } return result; } /* xmlparsing.c ends here */