javascript|xml| Generate XML
JavaScript generates XML
function XMLWriter ()
{
This. Xml=[];
This. Nodes=[];
This. State= "";
This. Formatxml = function (STR)
{
if (STR)
Return Str.replace (/&/g, "&"). Replace (/\ "/g," ""). Replace (/</g, "<"). Replace (/>/g, ">");
Return ""
}
This. Beginnode = function (Name)
{
if (! Name) return;
if (this. state== "Beg") this. Xml.push (">");
This. State= "Beg";
This. Nodes.push (Name);
This. Xml.push ("<" +name);
}
This. Endnode = function ()
{
if (this. state== "Beg")
{
This. Xml.push ("/>");
This. Nodes.pop ();
}
else if (this. NODES.LENGTH>0)
This. Xml.push ("</" +this). Nodes.pop () + ">");
This. State= "";
}
This. Attrib = function (Name, Value)
{
if (this. state!= "Beg" | | ! Name) return;
This. Xml.push ("" +name+ "=\") +this. Formatxml (Value) + "\");
}
This. WriteString = function (Value)
{
if (this. state== "Beg") this. Xml.push (">");
This. Xml.push (this. Formatxml (Value));
This. State= "";
}
This. Node = function (Name, Value)
{
if (! Name) return;
if (this. state== "Beg") this. Xml.push (">");
This. Xml.push (value== "" | |! Value)? " < "+name+" "/>": "<" +name+ ">" +this. Formatxml (Value) + "</" +name+ ">");
This. State= "";
}
This. Close = function ()
{
while (this. NODES.LENGTH>0)
This. Endnode ();
This. State= "Closed";
}
This. ToString = function () {return this. Xml.join ("");}
}
XMLWriter
There are several ways to do this:
BeginNode (Name)
EndNode ()
Attrib (Name, Value)
WriteString (Value)
Node (Name, Value)
Close ()
ToString ()
BeginNode
Output a Label:
Xml. Beginnode ("Foo");
Xml. Beginnode ("Foo");
Xml. Attrib ("Bar", "Some Value");
writestring Method:
Xml. Node ("Mynode", "my Value");
Produces: <mynode>my value</mynode>
Xml. Beginnode ("Foo");
Xml. WriteString ("Hello World");
Xml. Endnode ();
Produces <foo>hello world</foo>
Node Method:
Xml. Endnode ();
Produces: <foo bar= "Some Value"/>
eg
function Writetest ()
{
Try
{
var xml=new XMLWriter ();
Xml. Beginnode ("Example");
Xml. Attrib ("Someattribute", "and Some Value");
Xml. Attrib ("Anotherattrib", "...");
Xml. WriteString ("This is a example of the JS XML WriteString method.");
Xml. Node ("Name", "Value");
Xml. Beginnode ("subnode");
Xml. Beginnode ("SubNode2");
Xml. Endnode ();
Xml. Beginnode ("SubNode3");
Xml. WriteString ("blah blah.");
Xml. Endnode ();
Xml. Close (); Takes care of unended tags.
The "Replace in" following line are only for making the XML look prettier in the textarea.
document.getElementById ("Exampleoutput"). Value=xml. ToString (). Replace (/</g, "\n<");
}
catch (ERR)
{
Alert ("Error:" + err.description);
}
return false;
}
The generated XML is:
<example someattribute= "and Some Value" anotherattrib= "..." >this is a Example of the JS XML WriteString method.
<name>value
</Name>
<SubNode>
<SubNode2/>
<subnode3>blah blah.
</SubNode3>
</SubNode>
</Example>