2015-10-05 65 views

回答

1

以下是XML到JSON轉換的簡單代碼。

function xmlToJson(xml) { 
    // Create the return object 
    var obj = {}; 
    if (xml.nodeKind() == "element") { 
     if (xml.attributes().length() > 0) { 
      for (var j = 0; j < xml.attributes().length(); j++) { 
       var attributeName = xml.attributes()[j].name(); 
       obj[attributeName] = String(xml.attributes()[j]); 
      } 
     } 
    } else if (xml.nodeKind() == "text") { 
     obj['text'] = xml.text(); 
    } 
    if (xml.children()) { 
     for (var i = 0; i < xml.children().length(); i++) { 
      var item = xml.child(i); 
      if (xml.children()[i].nodeKind() == "text") { 
       obj['text'] = xml.children()[i].toString(); 
      } else { 
       var nodeName = item.name(); 
       if (typeof(obj[nodeName]) == "undefined") { 
        obj[nodeName] = xmlToJson(item); 
       } else { 
        if (typeof(obj[nodeName].push) == "undefined") { 
         var old = obj[nodeName]; 
         obj[nodeName] = []; 
         obj[nodeName].push(old); 
        } 
        obj[nodeName].push(xmlToJson(item)); 
       } 
      } 
     } 
    } 
    return obj; 
};