parse2.pas 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. program parse2;
  13. {$mode objfpc}
  14. uses
  15. xml2,
  16. exutils;
  17. (**
  18. * exampleFunc:
  19. * @filename: a filename or an URL
  20. *
  21. * Parse and validate the resource and free the resulting tree
  22. *)
  23. procedure exampleFunc(const filename: PAnsiChar);
  24. var
  25. ctxt: xmlParserCtxtPtr; (* the parser context *)
  26. doc: xmlDocPtr; (* the resulting document tree *)
  27. begin
  28. (* create a parser context *)
  29. ctxt := xmlNewParserCtxt();
  30. if ctxt = Nil then
  31. begin
  32. printfn('Failed to allocate parser context');
  33. Exit;
  34. end;
  35. (* parse the file, activating the DTD validation option *)
  36. doc := xmlCtxtReadFile(ctxt, filename, Nil, XML_PARSE_DTDVALID);
  37. (* check if parsing succeeded *)
  38. if doc = Nil then
  39. printfn('Failed to parse %s', [filename])
  40. else
  41. begin
  42. (* check if validation succeeded *)
  43. if ctxt^.valid = 0 then
  44. printfn('Failed to validate %s', [filename]);
  45. (* free up the resulting document *)
  46. xmlFreeDoc(doc);
  47. end;
  48. (* free up the parser context *)
  49. xmlFreeParserCtxt(ctxt);
  50. end;
  51. begin
  52. if ParamCount <> 1 then
  53. Halt(1);
  54. (*
  55. * this initialize the library and check potential ABI mismatches
  56. * between the version it was compiled for and the actual shared
  57. * library used.
  58. *)
  59. LIBXML_TEST_VERSION;
  60. exampleFunc(PAnsiChar(ParamStr(1)));
  61. (*
  62. * Cleanup function for the XML library.
  63. *)
  64. xmlCleanupParser();
  65. (*
  66. * this is to debug memory for regression tests
  67. *)
  68. xmlMemoryDump();
  69. end.