2014-04-28 95 views
0

我已經經歷了xml中的基礎知識,現在嘗試使用javascript解析xml數據。 我已經從w3schools &獲得了幫助,編寫了下面的代碼,但沒有發生解析,並且顯示了一個空白頁面。請幫助...使用Javascript解析XML數據

的xml文件現在用的就是的books.xml

<bookstore> 
<book category="cooking"> 
<title lang="en">Everyday Italian</title> 
<author>Giada De Laurentiis</author> 
<year>2005</year> 
<price>30.00</price> 
</book> 
<book category="children"> 
<title lang="en">Harry Potter</title> 
<author>J K. Rowling</author> 
<year>2005</year> 
<price>29.99</price> 
</book> 
</bookstore> 

的Html代碼是:

<!DOCTYPE html> 
<html> 
<head> 
<script> 

function loadXMLDoc(filename) 
{ 
if (window.XMLHttpRequest) 
    { 
    xhttp=new XMLHttpRequest(); 
    } 

xhttp.open("GET",filename,false); 
xhttp.send(); 
return xhttp.responseXML; 
} 


</script> 
</head> 
<body> 
<script> 

var xmlDoc=loadXMLDoc("C:/Users/A/Desktop/books.xml"); 

document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue + "<br>"); 
document.write(xmlDoc.getElementsByTagName("author")[0].childNodes[0].nodeValue + "<br>"); 
document.write(xmlDoc.getElementsByTagName("year")[0].childNodes[0].nodeValue); 


</script> 

</body> 

</html> 
+0

除非你出於學術好奇,否則你最好使用預先編寫的庫,比如jQuery。請點擊此處:https://api.jquery.com/jQuery.parseXML/ –

+1

請勿使用'document.write',請參閱[規範]中的警告(http://www.w3.org/TR/html5 /dom.html#document.write%28%29)。改用DOM方法。 – Oriol

+0

是你的'xmlDoc'一個XML對象嗎?做一個'console.log(xmlLog);'確定。 – Ibu

回答

0

我試過你的代碼,它作品(我在Mac OSX上使用Mozilla Firefox 28)。

請記住,在Windows系統上,目錄分隔符是反斜槓\而不是斜槓/ 嘗試在xml路徑中更改該目錄。也許你看到一個空白頁面,因爲你沒有提供回退,以防你的AJAX請求無法找到該XML。如果您使用的是Firebug,則在嘗試獲取該xml時應該會看到「404 Not Found」錯誤。

+0

我無法理解,無論我嘗試的代碼是不是在我的電腦工作。試用Firefox也:( – Anuraag

+0

現在有了。 – Anuraag

+0

將文件目標更改爲「file:/// C:/Users/A/Desktop/books.xml」 – Anuraag