elements.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. #if defined(__amigaos__) && defined(__USE_INLINE__)
  10. #include <proto/expat.h>
  11. #endif
  12. #ifdef XML_LARGE_SIZE
  13. #if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
  14. #define XML_FMT_INT_MOD "I64"
  15. #else
  16. #define XML_FMT_INT_MOD "ll"
  17. #endif
  18. #else
  19. #define XML_FMT_INT_MOD "l"
  20. #endif
  21. static void XMLCALL
  22. startElement(void *userData, const char *name, const char **atts)
  23. {
  24. int i;
  25. int *depthPtr = (int *)userData;
  26. for (i = 0; i < *depthPtr; i++)
  27. putchar('\t');
  28. puts(name);
  29. *depthPtr += 1;
  30. }
  31. static void XMLCALL
  32. endElement(void *userData, const char *name)
  33. {
  34. int *depthPtr = (int *)userData;
  35. *depthPtr -= 1;
  36. }
  37. int
  38. main(int argc, char *argv[])
  39. {
  40. char buf[BUFSIZ];
  41. XML_Parser parser = XML_ParserCreate(NULL);
  42. int done;
  43. int depth = 0;
  44. XML_SetUserData(parser, &depth);
  45. XML_SetElementHandler(parser, startElement, endElement);
  46. do {
  47. int len = (int)fread(buf, 1, sizeof(buf), stdin);
  48. done = len < sizeof(buf);
  49. if (XML_Parse(parser, buf, len, done) == XML_STATUS_ERROR) {
  50. fprintf(stderr,
  51. "%s at line %" XML_FMT_INT_MOD "u\n",
  52. XML_ErrorString(XML_GetErrorCode(parser)),
  53. XML_GetCurrentLineNumber(parser));
  54. return 1;
  55. }
  56. } while (!done);
  57. XML_ParserFree(parser);
  58. return 0;
  59. }