2013-07-21 23 views
0

我想用java腳本解析一個簡單的xml文件。當我將文件加載到webrowser「Chrome」中時,該頁面不顯示任何內容。 enter image description here當使用Javascript解析XML文件時,Web瀏覽器不顯示任何東西

請讓我知道我的錯誤是什麼。

XML文件

< ?xml version="1.0" encoding="UTF-8" ?> 
<company> 
    <employee id="001" >John</employee> 
    <turnover> 
     <year id="2000">100,000</year> 
     <year id="2001">140,000</year> 
     <year id="2002">200,000</year> 
    </turnover> 
</company> 

JavaScript分析器

Read XML in Microsoft Browsers</title> 
<script type="text/javascript"> 
var xmlDoc; 
function loadxml() 
{ 
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); 
    xmlDoc.async = false; 
    xmlDoc.onreadystatechange = readXML; /* to be notified when the state changes */ 
    xmlDoc.load("C:\Users\Amr\Desktop\files\xml.xml"); 
} 

function readXML() 
{ 
    if(xmlDoc.readyState == 4) 
    { 
    //Using documentElement Properties 
    //Output company 
    alert("XML Root Tag Name: " + xmlDoc.documentElement.tagName); 

    //Using firstChild Properties 
    //Output year 
    alert("First Child: " + xmlDoc.documentElement.childNodes[1].firstChild.tagName); 

//Using lastChild Properties 
//Output average 
alert("Last Child: " + xmlDoc.documentElement.childNodes[1].lastChild.tagName); 

//Using nodeValue and Attributes Properties 
//Here both the statement will return you the same result 
//Output 001 
alert("Node Value: " + xmlDoc.documentElement.childNodes[0].attributes[0].nodeValue); 
alert("Node Value: " + xmlDoc.documentElement.childNodes[0].attributes.getNamedItem("id").nodeValue); 

//Using getElementByTagName Properties 
//Here both the statement will return you the same result 
//Output 2000 
alert("getElementsByTagName: " + xmlDoc.getElementsByTagName("year")[0].attributes.getNamedItem("id").nodeValue); 

//Using text Properties 
//Output John 
alert("Text Content for Employee Tag: " + xmlDoc.documentElement.childNodes[0].text); 

//Using hasChildNodes Properties 
//Output True 
alert("Checking Child Nodes: " + xmlDoc.documentElement.childNodes[0].hasChildNodes); 
    } 

回答

2

那是因爲你正在使用的ActiveX對象做解析,它只能在IE瀏覽器。由於您是從文件加載XML,所以請改用XMLHttpRequest。它在IE 7以來版本的Chrome瀏覽器,火狐,Safari等 這裏一起實現對你是一個很好的解釋和一些democode: http://wordsfromgeek.blogspot.se/2008/11/xml-dom-in-chrome.html?m=1

+0

我試圖加載在IE文件,但它沒有工作 –

+0

如果您查看控制檯下的開發人員工具欄,它會給你什麼錯誤消息? –

+0

請看附圖 –

相關問題