日期:2014-05-16  浏览次数:20377 次

在Javascript中解析内存中的xml字符串并转换为JSON

由于一些不可抗力因素导致我需要将一个从js函数中返回的字符串变量(内容为xml)转换为IXMLDOMDocument2,进而转换为json,需要能跨浏览器,网上搜了很多种方法,加载xml的时候都必须用ajax加载外部文件中的xml,浪了半天,终于结果了:

==========

//解析xml字符串变量为IXMLDOMDocument2

  function parseXML(data){
   var xml,tmp;
   if ( window.DOMParser ) { // Standard
    tmp = new DOMParser();
    xml = tmp.parseFromString( data , "text/xml" );
   } else { // IE
    xml = new ActiveXObject( "Microsoft.XMLDOM" );
    xml.async = "false";
    xml.loadXML( data );
   }

   tmp = xml.documentElement;

   if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
        return null;
   }

   return xml;
  }

?将IXMLDOMDocument2转换为JSON,参数为IXMLDOMDocument2对象

function toJson (obj){
if (this==null) return null;
var retObj = new Object;
buildObjectNode(retObj,/*jQuery*/obj);
return retObj;
function buildObjectNode(cycleOBJ,/*Element*/elNode){
/*NamedNodeMap*/
var nodeAttr=elNode.attributes;
if(nodeAttr != null){
if (nodeAttr.length&&cycleOBJ==null) cycleOBJ=new Object; 
for(var i=0;i<nodeAttr.length;i++){
cycleOBJ[nodeAttr[i].name]=nodeAttr[i].value;
}
}
var nodeText="text";
if (elNode.text==null) nodeText="textContent";
/*NodeList*/
var nodeChilds=elNode.childNodes;
if(nodeChilds!=null){
if (nodeChilds.length&&cycleOBJ==null) cycleOBJ=new Object; 
for(var i=0;i<nodeChilds.length;i++){
if (nodeChilds[i].tagName!=null){
if (nodeChilds[i].childNodes[0]!=null&&nodeChilds[i].childNodes.length<=1&&(nodeChilds[i].childNodes[0].nodeType==3||nodeChilds[i].childNodes[0].nodeType==4)){
if (cycleOBJ[nodeChilds[i].tagName]==null){
cycleOBJ[nodeChilds[i].tagName]=nodeChilds[i][nodeText];
}else{
if (typeof(cycleOBJ[nodeChilds[i].tagName])=="object"&&cycleOBJ[nodeChilds[i].tagName].length){
cycleOBJ[nodeChilds[i].tagName][cycleOBJ[nodeChilds[i].tagName].length]=nodeChilds[i][nodeText];
}else{
cycleOBJ[nodeChilds[i].tagName]=[cycleOBJ[nodeChilds[i].tagName]];
cycleOBJ[nodeChilds[i].tagName][1]=nodeChilds[i][nodeText];
}
}
}else{
if (nodeChilds[i].childNodes.length){
if (cycleOBJ[nodeChilds[i].tagName]==null){
cycleOBJ[nodeChilds[i].tagName]=new Object;
buildObjectNode(cycleOBJ[nodeChilds[i].tagName],nodeChilds[i]);
}else{
if (cycleOBJ[nodeChilds[i].tagName].length){
cycleOBJ[nodeChilds[i].tagName][cycleOBJ[nodeChilds[i].tagName].length]=new Object;
buildObjectNode(cycleOBJ[nodeChilds[i].tagName][cycleOBJ[nodeChilds[i].tagName].length-1],nodeChilds[i]);
}else{
cycleOBJ[nodeChilds[i].tagName]=[cycleOBJ[nodeChilds[i].tagName]];
cycleOBJ[nodeChilds[i].tagName][1]=new Object;
buildObjectNode(cycleOBJ[nodeChilds[i].tagName][1],nodeChilds[i]);
}
}
}else{
cycleOBJ[nodeChilds[i].tagName]=nodeChilds[i][nodeText];
}
}
}
}
}
}
}

?