日期:2014-04-28  浏览次数:23155 次

试了一下,xmlDoc.save()行不同,就试着用fso做了出来。
整理一下,供大家discuss。

由于用js操作本地xml文件之后save时会permission denied,所以据我所知就只能通过FSO来做。而用FSO,基本上就与文件能否是xml无关。

xml文件:

<root>
  <parent>
    <child1>one</child1>
    <child2>one</child2>
  </parent>
  <parent>
    <child1>two</child1>
    <child2>two</child2>
  </parent>
  <parent>
    ...
  </parent>
</root>

var temp;//要操作的数据

//添加节点
function add(root,parent,child1,child2){
 try{
  var fso = new ActiveXObject("Scripting.FileSystemObject");
  var fileOpen = fso.OpenTextFile("*.xml",1);
  var fileContent = fileOpen.ReadAll();
  fileOpen.close();

  if(fileContent.toString().indexOf(temp) !=-1){
   alert(temp+"was already in data.");
  }else{
   fileContent = fileContent.replace("</"+root+">","");
   fileContent += "<"+parent+"><"+child1+">";
   fileContent += ...;
   fileContent += "</"+child1+"><"+child2+">";
   fileContent += ...;
   fileContent += "</"+child2+"></"+parent+"></"+root+">";
   var fileWrite = fso.OpenTextFile("*.xml",2)
   fileWrite.write(fileContent);
   fileWrite.close();
   alert("add successfully!")
  }
 }catch(e){
  alert("fail to add.");
 }
}


//删除节点
function del(root,parent,child1,child2){
 try{
  if( confirm("are you sure to delete symbol:"+temp+"?" ) ){
   var fso = new ActiveXObject("Scripting.FileSystemObject");
   var fileOpen = fso.OpenTextFile("*.xml",1);
   var fileContent = fileOpen.ReadAll();
   fileOpen.close();
   
   var parentArr = fileContent.split("</"+parent+">");
   var symbolPos = -2;//不一定是2,只需<0即可
   for (var i=0; i<parentArr.length-1; i++){
    if(parentArr[i].indexOf(temp) != -1){
    symbolPos = i;
    continue;
    }
    parentArr[i] += "</"+parent+">"; 
   }
   if (symbolPos == -2){
    alert(temp+" not found in data.")
   }else{
    if(symbolPos == 0){
     parentArr[0] = "<"+root+">";
    }else{
     parentArr.splice(symbolPos,1);
    }
    fileContent = parentArr.toString().replace(/,/g,"")
    var fileWrite = fso.OpenTextFile("*.xml",2);
    fileWrite.write(fileContent);
    fileWrite.close();
    alert("deleted successfully!");
   }
  }
 }catch(e){
  alert("fail to delete.");
 }

基本思路:

添加节点
1:读入原先xml文件所有字符,保存为fileContent;
2:去除根结点的封闭节点,即</root>;
3:fileContent += <parent><child1>..</child1><child2>...</child2></parent>;
4:fileContent += </root>;
5:写入xml文件,关闭。
基本上就是用手动输入来代替xml的CreateNode。

删除节点
1:读入原先xml文件所有字符,保存为fileContent;
2:以parent来