以学生信息为例子。
用到了3个文件studentINFO.html,studentinfo.xml,studentinfoNew.xml
studentinfo.xml---学生信息
<?xml version="1.0"?>
<studentlist>
<student>
<id>213</id>
<name>asd</name>
<age>sdf</age>
</student>
<student>
<id>rfwer</id>
<name></name>
<age></age>
</student></studentlist>
studentinfoNew.xml---新添加的空的学生信息模版
<?xml version="1.0" encoding="gb2312"?>
<studentlist>
<student>
<id></id>
<name></name>
<age></age>
</student>
</studentlist>
studentINFO.html---增删改的用户UI
<HTML><BODY bgColor=#a1bae6>
<XML id=xmldso src="studentinfo.xml"></XML>
<XML id=studentinfoNew></XML> <!--加?xml数据-->
<SCRIPT Language=JavaScript>
studentinfoNew.async = false;
studentinfoNew.load("studentinfoNew.xml");
function display(){
var doc=xmldso.XMLDocument;
alert(doc.xml);
}
function save(){
try{
var doc=xmldso.XMLDocument;
alert(doc.xml);
var strFile="";
var fso, f, ts;
var s="E://習う//XML//javascript_ReadWriteXML//studentinfo.xml";
var ForReading = 1, ForWriting = 2, ForAppending = 8;
var TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0;
fso = new ActiveXObject("Scripting.FileSystemObject");
if(!fso.FileExists(s)){
alert(s+" is not exist!");
}else{
f = fso.GetFile(s);
ts = f.OpenAsTextStream(ForWriting, TristateUseDefault);
ts.WriteLine(doc.xml);
ts.Close( );
}
}catch(e){
alert(e);
}
}
//增加??;
function addID(){
var doc=xmldso.XMLDocument;
var rootnode=doc.documentElement;
var sortNode = rootnode.selectNodes("//id");
var currentid = sortNode.length-1;
var cc="";
if(currentid==-1){
var node= studentinfoNew.documentElement.childNodes(0).cloneNode(true);
xmldso.documentElement.appendChild(node);
}else{
cc=sortNode.item(currentid).text;
if ((cc=="aa")||(cc=="")){
alert("?将最后一行数据填写完?后再增加新的??!");
}else{
var node= studentinfoNew.documentElement.childNodes(0).cloneNode(true);
xmldso.documentElement.appendChild(node);
}
}
}
//?除??
function delID(whichFld){
var doc=xmldso.XMLDocument;
var rootnode=doc.documentElement;
var sortNode = rootnode.selectNodes("//student");
if(sortNode.length==1){
alert("can not do delete when there is only 1 record");
return;
}
var sortNode = xmldso.selectSingleNode("//student/id[text()='"+whichFld+"']");
try{
sortNode.parentNode.parentNode.removeChild(sortNode.parentNode);
}catch(e){
}
}
</SCRIPT>
<center><b>student-studentlist</b><br><br>
<TABLE id="table" DATASRC='#xmldso' BORDER CELLPADDING=3>
<!--?行数据?定-->
<THEAD><TH>ID</TH><TH>id</TH><TH>name</TH><TH>age</TH></THEAD>
<TR>
<TD><acronym title='点?即可?除???'><INPUT TYPE=button size=4 DATAFLD="id" οnclick="delID(this.value)"></acronym></TD>
<TD><INPUT TYPE=TEXT DATAFLD="id"></TD>
<TD><INPUT TYPE=TEXT DATAFLD="name"></TD>
<TD><INPUT TYPE=TEXT DATAFLD="age"></TD>
</TR>
</TABLE>
<INPUT TYPE=BUTTON name=dd id=dd VALUE="add" οnclick="addID();">
<INPUT TYPE=BUTTON name=cc id=cc VALUE="save" οnclick="save()">
<INPUT TYPE=BUTTON name=ee id=ee VALUE="display" οnclick="display()"></center></BODY></HTML>