views:

30

answers:

2

What is the best strategy of making Abstract Syntax Trees serializable to an XML File?

+1  A: 

Chapter "ANTLR Trees vs. Custom Trees" on this web page shows an example of a antlr grammar, some input and the formatted output of the AST for the given input. The chapter contains a link to a C++ program to produce this formatted output.

It is not xml but pretty close and could be a good basis to start with.

Andreas_D
+1  A: 

Walk the AST recursively starting at the root.

When descending to a node of type X, print an opening tag:

 <X>

then descend into children left-to-right and print their content. After processing all the childen, print a closing tag:

 </X>

At a leaf node of type L, print

 <L value="abc"/>

with possibly attribute values of interest.

Done.

If you keep track of recursion nesting, you can print out the tag start and ends with leading *recursion_depth* spaces, and follow with a newline. Then your XML will be nicely nested.

Ira Baxter