本文以一个简单的登录界面演示,有三个文件,login.html, XMLWriter.js, login.js。
login.html
<html>
<head>
<script src = "XMLWriter.js" ></script>
<script src = "login.js" ></script>
</head>
<body>
<form>
用户名:<input id = "uname" type = "text"></input>
<br/>
密 码:<input id = "pword" type = "password"></input>
<br/>
<button id = "aa">submit</button>
</form>
<br/>
</body>
</html>
XMLWriter.js
function XMLWriter() { this.XML=['<?xml version="1.0" encoding="UTF-8"?>']; 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("");} }
login.js
function createXML(){ try { XML=new XMLWriter(); XML.BeginNode("Login"); XML.Node("Name", document.getElementById("uname").value); XML.BeginNode("password"); XML.WriteString(document.getElementById("pword").value); XML.EndNode(); XML.Close(); // Takes care of unended tags. // The replace in the following line are only for making the XML look prettier in the textarea. alert(XML.ToString().replace(/</g,"\n<");); } catch(Err) { alert("Error: " + Err.description); } } window.οnlοad=function(){ document.getElementById("aa").οnclick=createXML; }
XMLWriter
有以下几个方法:
BeginNode (Name)
EndNode ()
Attrib (Name, Value)
WriteString (Value)
Node (Name, Value)
Close ()
ToString ()
BeginNode
输出一个标签:
XML.BeginNode(“Foo”);
XML.BeginNode(“Foo”);
XML.Attrib(“Bar”, “Some Value”);
WriteString 方法:
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 方法:
XML.EndNode();
//Produces: <Foo Bar=”Some Value” />