Traversing XML Documents

When processing particular information in an XML document, you may often need to navigate a tree from the root to the deepest leaf element in document order.

If you want to traverse (walk through) the complete tree in document order, you can use the childNodes property array of the JadeXMLNode class, which contains the immediate children of each node.

The following examples read a document and print the names of the elements in that document, indented to show the hierarchy.

listChildren(elt: JadeXMLElement; depth: Integer);
vars
    i     : Integer;
    str   : String;
    child : JadeXMLNode;
begin
    foreach i in 1 to depth do
        str := str & '  ';
    endforeach;
    write str & elt.tagName;
    foreach child in elt.childNodes where child.isKindOf(JadeXMLElement) do
        listChildren(child.JadeXMLElement, depth + 1);
    endforeach;
end;

listElements(fileName: String);
vars
    doc : JadeXMLDocument;
begin
    create doc;
    doc.parseFile(fileName);
    listChildren(doc.rootElement, 0);
    delete doc;
end;

The following is output when the listElements method is run on the library1.xml document.

library
  book
    title
    author
  book
    title
    author

As an example of a more-general approach for traversing a tree, you could define the following recursive method of the JadeXMLNode class to traverse a sub-tree of the document.

walk();
vars
    child: JadeXMLNode;
begin
    processNode;                  // process this node
    foreach child in childNodes do
        child.walk;
    endforeach;
end;

In the above example, the polymorphic Node::processNode method would provide the specific code to process each type of node. To process the whole document, simply call the following.

doc.walk;