summaryrefslogtreecommitdiff
path: root/packages/libxml/examples/tree1.pas
blob: eb271572691c5d22c26c1b2aa153cc36cc1ef547 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
(**
 * section: Tree
 * synopsis: Navigates a tree to print element names
 * purpose: Parse a file to a tree, use xmlDocGetRootElement() to
 *          get the root element, then walk the document and print
 *          all the element name in document order.
 * usage: tree1 filename_or_URL
 * test: tree1 test2.xml > tree1.tmp ; diff tree1.tmp tree1.res ; rm tree1.tmp
 * author: Dodji Seketeli
 * copy: see Copyright for the status of this software.
 *)

program tree1;

{$mode objfpc}

uses
  ctypes,
  xml2,
  exutils,
  SysUtils;

procedure print_element_names(a_node: xmlNodePtr);
var
  cur_node: xmlNodePtr;
begin
  cur_node := a_node;
  while assigned(cur_node) do
  begin
    if cur_node^._type = XML_ELEMENT_NODE then
      printfn('node type: Element, name: %s', [cur_node^.name]);

    print_element_names(cur_node^.children);

    cur_node := cur_node^.next;
  end;
end;

var
  doc: xmlDocPtr;
  root_element: xmlNodePtr;

begin
  if paramCount <> 1 then
    halt(1);

  (*
   * this initialize the library and check potential ABI mismatches
   * between the version it was compiled for and the actual shared
   * library used.
   *)
  LIBXML_TEST_VERSION;

  (* parse the file and get the DOM *)
  doc := xmlReadFile(pchar(paramStr(1)), nil, 0);

  if not assigned(doc) then
  begin
    printfn('error: could not parse file %s', [paramStr(1)]);
    halt(1);
  end;

  (* Get the root element node *)
  root_element := xmlDocGetRootElement(doc);

  print_element_names(root_element);

  (* free the document *)
  xmlFreeDoc(doc);

  (*
   * Free the global variables that may
   * have been allocated by the parser.
   *)
  xmlCleanupParser();
end.