xml2ns0.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * xml2ns0.c
  3. *
  4. * Created on: 21.04.2014
  5. * Author: mrt
  6. */
  7. #include <expat.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. typedef struct parent {
  11. int depth;
  12. void* obj[20];
  13. } parent_t;
  14. void startElement(void * data, const char *el, const char **attr) {
  15. parent_t* p = (parent_t*) data;
  16. int i, j;
  17. if (p->depth==0) { printf("new %s --\n", el); }
  18. p->obj[p->depth] = el;
  19. for (i = 0; attr[i]; i += 2) {
  20. for (j = 0; j < p->depth; j++) {
  21. printf("%s.",p->obj[j]);
  22. }
  23. printf("%s='%s'\n", attr[i], attr[i + 1]);
  24. }
  25. p->depth++;
  26. } /* End of start handler */
  27. void handleText(void * data, const char *s, int len) {
  28. parent_t* p = (parent_t*) data;
  29. int j, i;
  30. if (len > 0) {
  31. // process only strings that are not entirely built of whitespaces
  32. for (i=0; i<len;i++) {
  33. if (! isspace(s[i])) {
  34. for (j = 0; j < p->depth; j++) {
  35. printf("%s.",p->obj[j]);
  36. }
  37. printf("%s={%d,'%.*s'}\n", "Value", len, len, s);
  38. break;
  39. }
  40. }
  41. }
  42. } /* End of text handler */
  43. void endElement(void *data, const char *el) {
  44. parent_t* p = (parent_t*) data;
  45. p->depth--;
  46. } /* End of end handler */
  47. int main()
  48. {
  49. char buf[1024];
  50. int len; /* len is the number of bytes in the current bufferful of data */
  51. int done;
  52. parent_t p;
  53. p.depth = 0;
  54. XML_Parser parser = XML_ParserCreate(NULL);
  55. XML_SetUserData(parser, &p);
  56. XML_SetElementHandler(parser, startElement, endElement);
  57. XML_SetCharacterDataHandler(parser, handleText);
  58. while ((len = read(0,buf,1024)) > 0) {
  59. if (!XML_Parse(parser, buf, len, (len<1024))) {
  60. return 1;
  61. }
  62. }
  63. XML_ParserFree(parser);
  64. return 0;
  65. }