I had a simple idea today, about how to stream out data – not directly to a text stream, but to a DOM Document. The idea is very simple and proved to give very elegant and simple code that is easy to understand and write. Here’s how it goes.
Note: The idea is used in an MBS NAV solution where the C/AL programming language is used. It is an extremely simple and monotonous language with very little freedom. One does not have powerful language constructs to ease the process further.
There are three fundamental methods involved in the API and the API only cares about elements and text. The three core functions involved are
These methods all work on a context element that acts like a cursor. The down method creates a child element in the tree and sets the context node to it. The set method creates a new child element in the context element and creates a text node inside that. The up method simply sets the context element to the parent of the context element. The idea is very simple, but can of course be extended to deal with QNames, CDATA, PI, etc.
As an example of how one might create the following document
one can simply write
That’s it. Quite simple and very readable.
One might also introduce an XML-ish close method
This would traverse upwards in the structure until it met the element and if not, throw an error message.