reader1.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /**
  2. * section: xmlReader
  3. * synopsis: Parse an XML file with an xmlReader
  4. * purpose: Demonstrate the use of xmlReaderForFile() to parse an XML file
  5. * and dump the informations about the nodes found in the process.
  6. * (Note that the XMLReader functions require libxml2 version later
  7. * than 2.6.)
  8. * usage: reader1 <filename>
  9. * test: reader1 test2.xml > reader1.tmp ; diff reader1.tmp reader1.res ; rm reader1.tmp
  10. * author: Daniel Veillard
  11. * copy: see Copyright for the status of this software.
  12. */
  13. #include <stdio.h>
  14. #include <libxml/xmlreader.h>
  15. #ifdef LIBXML_READER_ENABLED
  16. /**
  17. * processNode:
  18. * @reader: the xmlReader
  19. *
  20. * Dump information about the current node
  21. */
  22. static void
  23. processNode(xmlTextReaderPtr reader) {
  24. const xmlChar *name, *value;
  25. name = xmlTextReaderConstName(reader);
  26. if (name == NULL)
  27. name = BAD_CAST "--";
  28. value = xmlTextReaderConstValue(reader);
  29. printf("%d %d %s %d %d",
  30. xmlTextReaderDepth(reader),
  31. xmlTextReaderNodeType(reader),
  32. name,
  33. xmlTextReaderIsEmptyElement(reader),
  34. xmlTextReaderHasValue(reader));
  35. if (value == NULL)
  36. printf("\n");
  37. else {
  38. if (xmlStrlen(value) > 40)
  39. printf(" %.40s...\n", value);
  40. else
  41. printf(" %s\n", value);
  42. }
  43. }
  44. /**
  45. * streamFile:
  46. * @filename: the file name to parse
  47. *
  48. * Parse and print information about an XML file.
  49. */
  50. static void
  51. streamFile(const char *filename) {
  52. xmlTextReaderPtr reader;
  53. int ret;
  54. reader = xmlReaderForFile(filename, NULL, 0);
  55. if (reader != NULL) {
  56. ret = xmlTextReaderRead(reader);
  57. while (ret == 1) {
  58. processNode(reader);
  59. ret = xmlTextReaderRead(reader);
  60. }
  61. xmlFreeTextReader(reader);
  62. if (ret != 0) {
  63. fprintf(stderr, "%s : failed to parse\n", filename);
  64. }
  65. } else {
  66. fprintf(stderr, "Unable to open %s\n", filename);
  67. }
  68. }
  69. int main(int argc, char **argv) {
  70. if (argc != 2)
  71. return(1);
  72. /*
  73. * this initialize the library and check potential ABI mismatches
  74. * between the version it was compiled for and the actual shared
  75. * library used.
  76. */
  77. LIBXML_TEST_VERSION
  78. streamFile(argv[1]);
  79. /*
  80. * Cleanup function for the XML library.
  81. */
  82. xmlCleanupParser();
  83. /*
  84. * this is to debug memory for regression tests
  85. */
  86. xmlMemoryDump();
  87. return(0);
  88. }
  89. #else
  90. int main(void) {
  91. fprintf(stderr, "XInclude support not compiled in\n");
  92. exit(1);
  93. }
  94. #endif