如何在JS中实现相互转换XML和JSON

2020-05-16 18:46:55易采站长站整理

            var node = xml.childNodes.item(i);
            var item = this.convert(node);
            if(item) {
                items.push(item);
            }
        }
        if(items.length > 0) {
            obj.items = items;
        }
    }
    return obj;
};

JSON转换为XML:


function JsonToXml() {
 this.result = [];
}
JsonToXml.prototype.spacialChars = [“&”,”<“,”>”,”””,”‘”];
JsonToXml.prototype.validChars = [“&”,”<“,”>”,”””,”‘”];
JsonToXml.prototype.toString = function(){
 return this.result.join(“”);
};
JsonToXml.prototype.replaceSpecialChar = function(s){
    for(var i=0;i<this.spacialChars.length;i++){
        s=s.replace(new RegExp(this.spacialChars[i],”g”),this.validChars[i]);
    }
    return s;
};
JsonToXml.prototype.appendText = function(s){
    s = this.replaceSpecialChar(s);
    this.result.push(s);
};
JsonToXml.prototype.appendAttr = function(key, value){
    this.result.push(” “+ key +”=””+ value +”””);
};
JsonToXml.prototype.appendFlagBeginS = function(s){
 this.result.push(“<“+s);
};
JsonToXml.prototype.appendFlagBeginE = function(){
 this.result.push(“>”);
};
JsonToXml.prototype.appendFlagEnd = function(s){
 this.result.push(“</”+s+”>”);
};
JsonToXml.prototype.parse = function(json){
 this.convert(json);
 return this.toString();
};
JsonToXml.prototype.convert = function(obj) {
 var nodeName = obj.xtype || “item”;
 this.appendFlagBeginS(nodeName);
 var arrayMap = {};
 for(var key in obj) {
  var item = obj[key];
  if(key == “xtype”) {
   continue;
  }
  if(item.constructor == String) {
   this.appendAttr(key, item);
  }
  if(item.constructor == Array) {
   arrayMap[key] = item;