Friday, November 23, 2007

XML and javascript


Writing XML with JS
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.
The XMLWriter object can be created with the JavaScript new command like so:
var XML = new XMLWriter();
The XMLWriter object has the following public methods:
BeginNode (Name)
EndNode ()
Attrib (Name, Value)
WriteString (Value)
Node (Name, Value)
Close ()
ToString ()
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:
XML.BeginNode(“Foo”);
//Produces: ”. The object is smart enough to know if you have written any text or inner nodes out and will write “” 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.BeginNode(“Foo”);
XML.Attrib(“Bar”, “Some Value”);
XML.EndNode();
//Produces:
WriteString writes out a string value to the XML document as illustrated below:
XML.BeginNode(“Foo”);
XML.WriteString(“Hello World”);
XML.EndNode();
//Produces Hello World
The Node method writes out a named tag and value as illustrated below:
XML.Node(“MyNode”, “My Value”);
//Produces: My Value
The 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.
Finally, the ToString method returns the entire XML document as a single string (duh).

No comments: