parse2.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * section: Parsing
  3. * synopsis: Parse and validate an XML file to a tree and free the result
  4. * purpose: Create a parser context for an XML file, then parse and validate
  5. * the file, creating a tree, check the validation result
  6. * and xmlFreeDoc() to free the resulting tree.
  7. * usage: parse2 test2.xml
  8. * test: parse2 test2.xml
  9. * author: Daniel Veillard
  10. * copy: see Copyright for the status of this software.
  11. */
  12. #include <stdio.h>
  13. #include <libxml/parser.h>
  14. #include <libxml/tree.h>
  15. /**
  16. * exampleFunc:
  17. * @filename: a filename or an URL
  18. *
  19. * Parse and validate the resource and free the resulting tree
  20. */
  21. static void
  22. exampleFunc(const char *filename) {
  23. xmlParserCtxtPtr ctxt; /* the parser context */
  24. xmlDocPtr doc; /* the resulting document tree */
  25. /* create a parser context */
  26. ctxt = xmlNewParserCtxt();
  27. if (ctxt == NULL) {
  28. fprintf(stderr, "Failed to allocate parser context\n");
  29. return;
  30. }
  31. /* parse the file, activating the DTD validation option */
  32. doc = xmlCtxtReadFile(ctxt, filename, NULL, XML_PARSE_DTDVALID);
  33. /* check if parsing suceeded */
  34. if (doc == NULL) {
  35. fprintf(stderr, "Failed to parse %s\n", filename);
  36. } else {
  37. /* check if validation suceeded */
  38. if (ctxt->valid == 0)
  39. fprintf(stderr, "Failed to validate %s\n", filename);
  40. /* free up the resulting document */
  41. xmlFreeDoc(doc);
  42. }
  43. /* free up the parser context */
  44. xmlFreeParserCtxt(ctxt);
  45. }
  46. int main(int argc, char **argv) {
  47. if (argc != 2)
  48. return(1);
  49. /*
  50. * this initialize the library and check potential ABI mismatches
  51. * between the version it was compiled for and the actual shared
  52. * library used.
  53. */
  54. LIBXML_TEST_VERSION
  55. exampleFunc(argv[1]);
  56. /*
  57. * Cleanup function for the XML library.
  58. */
  59. xmlCleanupParser();
  60. /*
  61. * this is to debug memory for regression tests
  62. */
  63. xmlMemoryDump();
  64. return(0);
  65. }