簡體   English   中英

將xml轉換為JSON的問題

[英]Issue with conversion of xml to JSON

我按照以下教程 - http://davidwalsh.name/convert-xml-json獲取錯誤:

Uncaught exception: TypeError: 'xml.hasChildNodes' is not a function.

我不知道如何解決這個問題? 許多人在網站上發布了相同的內容。 但沒有運氣。

請幫忙。

代碼在這里:

<!DOCTYPE html>  
<html lang="en">  
<head>  
<title>Welcome</title>  

<script type="text/javascript">  
function myFun()  
{  
    alert("hi..");  
    var jsonText = JSON.stringify(xmlToJson("D:/Tech/data.xml"));  
    for(var i in jsonText)  
   {
        alert(i);
   }
}   

// Changes XML to JSON  
function xmlToJson(xml) {  

   // Create the return object  
   var obj = {};  

    if (xml.nodeType == 1) { // element  
        // do attributes  
        if (xml.attributes.length > 0) {  
        obj["@attributes"] = {};  
            for (var j = 0; j < xml.attributes.length; j++) {  
                var attribute = xml.attributes.item(j);  
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;  
            }  
        }  
     } else if (xml.nodeType == 3) { // text  
        obj = xml.nodeValue;  
    }

     // do children   
    if (xml.hasChildNodes()) {  
        for(var i = 0; i < xml.childNodes.length; i++) {  
            var item = xml.childNodes.item(i);  
            var nodeName = item.nodeName;  
            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;  
};  

 </script>  

</head>  

<body onload="myFun()">  
 Hello  
</body>  
</html>  

而data.xml就像這里:

<applications>  
<application id="backupparking">  
  <toplevel />   
 <contexts>  
 <context id="Idle" />   
 <context id="ABCD" />   
 <context id="EFGH" />   
 <context id="LMN">  
 <payload>  
  <member id="hi" type="string" />   
  </payload>  
  </context>  
  </application>  
  </applications>  

謝謝!

contexts標簽未正確關閉。

嘗試

<applications>  
<application id="backupparking">  
  <toplevel />   
 <contexts />  
 <context id="Idle" />   
 <context id="ABCD" />   
 <context id="EFGH" />   
 <context id="LMN">  
 <payload>  
  <member id="hi" type="string" />   
  </payload>  
  </context>  
  </application>  
  </applications> 

要么

<applications>  
<application id="backupparking">  
  <toplevel />   
 <contexts>  
 <context id="Idle" />   
 <context id="ABCD" />   
 <context id="EFGH" />   
 <context id="LMN">  
 <payload>  
  <member id="hi" type="string" />   
  </payload>  
  </context>  
 </contexts>  
  </application>  
  </applications> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM