tree1.pas 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. (**
  2. * section: Tree
  3. * synopsis: Navigates a tree to print element names
  4. * purpose: Parse a file to a tree, use xmlDocGetRootElement() to
  5. * get the root element, then walk the document and print
  6. * all the element name in document order.
  7. * usage: tree1 filename_or_URL
  8. * test: tree1 test2.xml > tree1.tmp ; diff tree1.tmp tree1.res ; rm tree1.tmp
  9. * author: Dodji Seketeli
  10. * copy: see Copyright for the status of this software.
  11. *)
  12. program tree1;
  13. {$mode objfpc}
  14. uses
  15. ctypes,
  16. xml2,
  17. exutils,
  18. SysUtils;
  19. procedure print_element_names(a_node: xmlNodePtr);
  20. var
  21. cur_node: xmlNodePtr;
  22. begin
  23. cur_node := a_node;
  24. while assigned(cur_node) do
  25. begin
  26. if cur_node^._type = XML_ELEMENT_NODE then
  27. printfn('node type: Element, name: %s', [cur_node^.name]);
  28. print_element_names(cur_node^.children);
  29. cur_node := cur_node^.next;
  30. end;
  31. end;
  32. var
  33. doc: xmlDocPtr;
  34. root_element: xmlNodePtr;
  35. begin
  36. if paramCount <> 1 then
  37. halt(1);
  38. (*
  39. * this initialize the library and check potential ABI mismatches
  40. * between the version it was compiled for and the actual shared
  41. * library used.
  42. *)
  43. LIBXML_TEST_VERSION;
  44. (* parse the file and get the DOM *)
  45. doc := xmlReadFile(pchar(paramStr(1)), nil, 0);
  46. if not assigned(doc) then
  47. begin
  48. printfn('error: could not parse file %s', [paramStr(1)]);
  49. halt(1);
  50. end;
  51. (* Get the root element node *)
  52. root_element := xmlDocGetRootElement(doc);
  53. print_element_names(root_element);
  54. (* free the document *)
  55. xmlFreeDoc(doc);
  56. (*
  57. * Free the global variables that may
  58. * have been allocated by the parser.
  59. *)
  60. xmlCleanupParser();
  61. end.