/xml2json.c

http://github.com/fizx/parsley · C · 47 lines · 37 code · 4 blank · 6 comment · 16 complexity · dab46e52e7dccd55774f77e2034cf241 MD5 · raw file

  1. #include "xml2json.h"
  2. static struct json_object * _xml2json(xmlNodePtr xml) {
  3. if(xml == NULL) return NULL;
  4. xmlNodePtr child;
  5. struct json_object * json = NULL;
  6. switch(xml->type) {
  7. case XML_ELEMENT_NODE:
  8. child = xml->children;
  9. if(xml->ns == NULL) {
  10. child = xml;
  11. // json_object_put(json);
  12. json = json_object_new_object();
  13. while(child != NULL) {
  14. json_object_object_add(json, child->name, xml2json(child->children));
  15. child = child->next;
  16. }
  17. } else if(!strcmp(xml->ns->prefix, "parsley")) {
  18. if(!strcmp(xml->name, "groups")) {
  19. // json_object_put(json);
  20. json = json_object_new_array();
  21. while(child != NULL) {
  22. json_object_array_add(json, xml2json(child->children));
  23. child = child->next;
  24. }
  25. } else if(!strcmp(xml->name, "group")) {
  26. // Implicitly handled by parsley:groups handler
  27. }
  28. }
  29. break;
  30. case XML_TEXT_NODE:
  31. json = json_object_new_string(xml->content);
  32. break;
  33. }
  34. return json;
  35. }
  36. /**
  37. * Handles a simplified xml
  38. */
  39. struct json_object * xml2json(xmlNodePtr xml) {
  40. struct json_object * json = _xml2json(xml);
  41. if(json == NULL) json = json_object_new_object();
  42. return json;
  43. }