XmlHelper.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "XmlHelper.h"
  2. #include <stdlib.h>
  3. #include <string.h>
  4. SearchResult *xml_result_alloc(int count, int max_results) {
  5. if (count <= 0 || max_results <= 0) {
  6. return NULL;
  7. }
  8. int actual = (count < max_results) ? count : max_results;
  9. return (SearchResult *)calloc(actual, sizeof(SearchResult));
  10. }
  11. void xml_result_free(SearchResult *results, int count) {
  12. if (!results) {
  13. return;
  14. }
  15. for (int i = 0; i < count; i++) {
  16. free(results[i].url);
  17. free(results[i].title);
  18. free(results[i].snippet);
  19. }
  20. free(results);
  21. }
  22. xmlXPathObjectPtr xml_xpath_eval(xmlXPathContextPtr ctx, const char *xpath) {
  23. if (!ctx || !xpath) {
  24. return NULL;
  25. }
  26. return xmlXPathEvalExpression((const xmlChar *)xpath, ctx);
  27. }
  28. char *xml_node_content(xmlNodePtr node) {
  29. if (!node) {
  30. return NULL;
  31. }
  32. char *content = (char *)xmlNodeGetContent(node);
  33. return content;
  34. }
  35. char *xpath_text(xmlDocPtr doc, const char *xpath) {
  36. if (!doc || !xpath) {
  37. return NULL;
  38. }
  39. xmlXPathContextPtr ctx = xmlXPathNewContext(doc);
  40. if (!ctx) {
  41. return NULL;
  42. }
  43. xmlXPathObjectPtr obj = xmlXPathEvalExpression((const xmlChar *)xpath, ctx);
  44. xmlXPathFreeContext(ctx);
  45. if (!obj || !obj->nodesetval || obj->nodesetval->nodeNr == 0) {
  46. if (obj)
  47. xmlXPathFreeObject(obj);
  48. return NULL;
  49. }
  50. xmlChar *content = xmlNodeGetContent(obj->nodesetval->nodeTab[0]);
  51. char *result = content ? strdup((char *)content) : NULL;
  52. if (content)
  53. xmlFree(content);
  54. xmlXPathFreeObject(obj);
  55. return result;
  56. }