Using the code
The object is called
XMLWriter. It automatically replaces invalid characters such as quotation marks or greater than signs with the appropriate XML values. However, it does not throw exceptions on invalid tag names, because the application I’m writing won’t have the possibility of producing invalid tag names. If you want to add tag-name validation to the object, it should not be a difficult task.
new command like so:
var XML = new XMLWriter();
XMLWriter object has the following public methods:
Attrib (Name, Value)
Node (Name, Value)
BeginNode writes out an opening tag, giving it the name that you pass the method. Below is an example, followed by the XML it would produce:
EndNode ends the current node (if any are still open). So following from the
BeginNode example, if we were to write
XML.EndNode(), the writer would write “/>”. The object is smart enough to know if you have written any text or inner nodes out and will write “</Foo>” if necessary.
Attrib writes out an attribute and value on the currently open node. Below is an example, followed by the XML it would produce:
XML.Attrib("Bar", "Some Value");
WriteString writes out a string value to the XML document as illustrated below:
Node method writes out a named tag and value as illustrated below:
XML.Node("MyNode", "My Value");
Close method does not necessarily need to be called, but it’s a good idea to do so. What it does is end any nodes that have not been ended.
ToString method returns the entire XML document as a single string (duh).
I’ve provided some sample code. The XMLWriter.js file contains all the code you will need to write XML. It is clean code, but uncommented. I’ve tested this code in IE 6.0 and FireFox 1.5.