way: the SAX one
Even if generically known as a good interface
to read data, SAX (at least in the Microsoft XML Parser 3.0) has also a set of
interfaces to write data. This is defined using the MXXMLWriter object in the
MSXML object model and, if you search for it in the latest MSDN Library, you
will find only 19 articles speaking of it.
From a programming point of view, the same code
of above using DOM is created using MXXMLWriter with the following
Dim lSAXReader As New
Dim lSAXWriter As New
'We need these variables for typecasting the
Dim lSAXContentHandler As
'That is just a helper
Dim lSAXAttributes As New
'Set handler variables to the writer so it implements the
Set lSAXContentHandler =
'do not include XML declaration, so that the file is like
lSAXWriter.omitXMLDeclaration = True
' Manually call necessary events to generate the XML
lSAXContentHandler.startElement "", "", "ROOT",
lSAXContentHandler.startElement "", "", "LEVEL1",
' Create and populate elements
lSAXContentHandler.startElement "", "", "VALUE11",
lSAXContentHandler.endElement "", "", "VALUE11"
lSAXContentHandler.startElement "", "", "LEVEL2",
lSAXContentHandler.startElement "", "", "VALUE21",
lSAXContentHandler.endElement "", "", "VALUE21"
lSAXContentHandler.endElement "", "", "LEVEL2"
lSAXContentHandler.endElement "", "", "LEVEL1"
lSAXContentHandler.endElement "", "", "ROOT"
It’s a little more verbose than DOM but is
still pretty readable and, with some more work, can be easily generalized to
render different data.
way: The Fast String one
At this point of my exploration I wondered some
time about the real need of some kind of object model when creating an XML file.
After all what we’re doing is creating a simple ASCII text file, hence maybe all
the overhead of keeping in memory a complex structure with nodes and elements is
not really needed. Problem is that string manipulation from Visual Basic is
really slow, and suddenly I remembered that our guest Francesco Balena some time
ago wrote a very performance wise string class for Visual Basic Programmer’s
Journal. After some digging around I got the CString.zip file that included the
CString class, a class that, using some Windows API, improves what is described
in tip bank.
Here is the code that creates a simple XML like
that shown in the program picture, the only point to note is the SetBufferSize
instruction that allocate the space to store the string. Here is set to a very
high value (20 Mb), but the best results are obtained if you declare to a size
comparable to that of the document you’re creating (if you know the structure of
your document, it is possible to calculate its size).
Dim lCS As New
It’s very compact, but also difficult to
generalize. Beside that, I’ve not considered all the features (like character
escaping or character sets support) that would make creating a well-formed XML
file a much more complex task.