I was writing yet another ASP page that returns XML when i thought to my self there has to be an easier way. When i first wrote pages like this i would just set the Response.ContentType="text/xml" and Response.Write an XML document. I soon ran into problems with encoding special characters and missing closing tags. Then i tried building a file using the DOM feature of the Microsoft parser. That involved a lot of oXML.createElements and .appendChilds and then i ran into a glut of objects to keep track of.
With my last VB.NET project, i encountered an object which would quickly let me write out an XML file and i didn't have to worry about encoding or the DOM. It was the XMLTextWriter Object. I wanted something just as easy to use in Classic ASP and this is what i came up with.
Don't get me wrong, this class isn't optimized for speed as the .NET equivalent is; It simply hides all the DOM work and makes the VBScript code to generate an XMLDocument a bit cleaner. It actually does create the DOM in memory rather than trying to properly manipulate a string. This method should ensure you output a xalid XML document above all else. Here's how you might call it...
Dim oXMLTextWriter
Set oXMLTextWriter=New cXMLTextWriter
With oXMLTextWriter
.WriteStartDocument "Sample"
.WriteStartElement "NodeOne"
.WriteStartElement "SubNodeOne"
.WriteAttributeString "IsNode","Yes"
.WriteString "Read & Write Node<yea!>"
.WriteEndElement
.WriteEndElement
.WriteElementString "NodeTwo","Node2Text"
.WriteEndDocument
End With
Response.write Server.HTMLEncode(oXMLTextWriter.xml)
The result looks something like this:
<Sample>
<NodeOne>
<SubNodeOne IsNode="Yes">
Read & Write Node<yea!></SubNodeOne>
</NodeOne>
<NodeTwo>
Node2Text</NodeTwo>
</Sample>
As you can see i didn't copy all of the properties and methods over exactly; just the ones i thought i would most likely use. There are also other error handling measures that should be taken that i've left out for simplicity.