Home > Articles > Programming > C/C++

  • Print
  • + Share This
From the author of Walking the Tree

Walking the Tree

Generating the HTML from the tree involves visiting each node in turn and emitting HTML for it. As you'd hopefully expect, this involves applying the visitor pattern. This particular implementation of the pattern is very simple. The visitor just has three methods, called with the tree node as an argument respectively when entering and leaving nodes and when visiting leaf nodes (the only ones that can contain characters, rather than other nodes).

Each of the tree node classes has a -visitWithVisitor: method that performs a depth-first traversal of the tree. Because HTML is very similar in structure to the text tree, most of the time this traversal just involves opening a tag when entering a node, closing it when exiting the node, and passing text straight through to the HTML writer.

The code actually visits the tree twice, once to collect cross-references and build the index and table of contents, and then again to generate the HTML. The visitor pattern is useful for structured data like this, because it makes it very easy to plug in simple classes that process the entire structure.

  • + Share This
  • 🔖 Save To Your Account