elements.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* This is simple demonstration of how to use expat. This program
  2. reads an XML document from standard input and writes a line with
  3. the name of each element to standard output indenting child
  4. elements by one tab stop more than their parent element.
  5. It must be used with Expat compiled for UTF-8 output.
  6. */
  7. #include <stdio.h>
  8. #include <expat.h>
  9. #ifdef XML_LARGE_SIZE
  10. #if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
  11. #define XML_FMT_INT_MOD "I64"
  12. #else
  13. #define XML_FMT_INT_MOD "ll"
  14. #endif
  15. #else
  16. #define XML_FMT_INT_MOD "l"
  17. #endif
  18. static void XMLCALL
  19. startElement(void *userData, const char *name, const char **atts)
  20. {
  21. int i;
  22. int *depthPtr = (int *)userData;
  23. (void)atts;
  24. for (i = 0; i < *depthPtr; i++)
  25. putchar('\t');
  26. puts(name);
  27. *depthPtr += 1;
  28. }
  29. static void XMLCALL
  30. endElement(void *userData, const char *name)
  31. {
  32. int *depthPtr = (int *)userData;
  33. (void)name;
  34. *depthPtr -= 1;
  35. }
  36. int
  37. main(int argc, char *argv[])
  38. {
  39. char buf[BUFSIZ];
  40. XML_Parser parser = XML_ParserCreate(NULL);
  41. int done;
  42. int depth = 0;
  43. (void)argc;
  44. (void)argv;
  45. XML_SetUserData(parser, &depth);
  46. XML_SetElementHandler(parser, startElement, endElement);
  47. do {
  48. size_t len = fread(buf, 1, sizeof(buf), stdin);
  49. done = len < sizeof(buf);
  50. if (XML_Parse(parser, buf, len, done) == XML_STATUS_ERROR) {
  51. fprintf(stderr,
  52. "%s at line %" XML_FMT_INT_MOD "u\n",
  53. XML_ErrorString(XML_GetErrorCode(parser)),
  54. XML_GetCurrentLineNumber(parser));
  55. return 1;
  56. }
  57. } while (!done);
  58. XML_ParserFree(parser);
  59. return 0;
  60. }