includexpath.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <![CDATA[
  2. #include <libxml/parser.h>
  3. #include <libxml/xpath.h>
  4. xmlDocPtr
  5. getdoc (char *docname) {
  6. xmlDocPtr doc;
  7. doc = xmlParseFile(docname);
  8. if (doc == NULL ) {
  9. fprintf(stderr,"Document not parsed successfully. \n");
  10. return NULL;
  11. }
  12. return doc;
  13. }
  14. xmlXPathObjectPtr
  15. getnodeset (xmlDocPtr doc, xmlChar *xpath){
  16. xmlXPathContextPtr context;
  17. xmlXPathObjectPtr result;
  18. context = xmlXPathNewContext(doc);
  19. if (context == NULL) {
  20. printf("Error in xmlXPathNewContext\n");
  21. return NULL;
  22. }
  23. result = xmlXPathEvalExpression(xpath, context);
  24. xmlXPathFreeContext(context);
  25. if (result == NULL) {
  26. printf("Error in xmlXPathEvalExpression\n");
  27. return NULL;
  28. }
  29. if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
  30. xmlXPathFreeObject(result);
  31. printf("No result\n");
  32. return NULL;
  33. }
  34. return result;
  35. }
  36. int
  37. main(int argc, char **argv) {
  38. char *docname;
  39. xmlDocPtr doc;
  40. xmlChar *xpath = (xmlChar*) "//keyword";
  41. xmlNodeSetPtr nodeset;
  42. xmlXPathObjectPtr result;
  43. int i;
  44. xmlChar *keyword;
  45. if (argc <= 1) {
  46. printf("Usage: %s docname\n", argv[0]);
  47. return(0);
  48. }
  49. docname = argv[1];
  50. doc = getdoc(docname);
  51. result = getnodeset (doc, xpath);
  52. if (result) {
  53. nodeset = result->nodesetval;
  54. for (i=0; i < nodeset->nodeNr; i++) {
  55. keyword = xmlNodeListGetString(doc, nodeset->nodeTab[i]->xmlChildrenNode, 1);
  56. printf("keyword: %s\n", keyword);
  57. xmlFree(keyword);
  58. }
  59. xmlXPathFreeObject (result);
  60. }
  61. xmlFreeDoc(doc);
  62. xmlCleanupParser();
  63. return (1);
  64. }
  65. ]]>