2012-04-19 101 views
0

我試圖將xml文件解析爲html。 所以我大氣壓與以下用Javascript解析XML

<script> 
    xmlDoc=new window.XMLHttpRequest(); 
    xmlDoc.open("GET","test",false); 
    xmlDoc.send(""); 
</script> 

去現在我想 「回聲」 的要求,我怎麼做,

<?xml version="1.0"?> 
<catalog> 
    <book id="bk101"> 
     <author>Gambardella, Matthew</author> 
     <title>XML Developer's Guide</title> 
     <genre>Computer</genre> 
     <price>44.95</price> 
     <publish_date>2000-10-01</publish_date> 
     <description>An in-depth look at creating applications 
     with XML.</description> 
    </book> 
</catalog> 

回答

2

試試這個:

xmlDoc=new window.XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP") || new ActiveXObject("Msxml2.XMLHTTP"); 
xmlDoc.onreadystatechange = function(){ 
    if(xmlDoc.readyState = 4 && xmlDoc.status == 200) // Success 
    { 
     document.write(xmlDoc.responseText); 
    } 
} 
xmlDoc.open("GET","test",false); 
xmlDoc.send(""); 
+0

嗨,首先感謝,至今我無法得到它的工作。我仍然看到一個空白頁面,並且responseText仍然是「」任何想法? – 2012-04-19 13:03:59

+0

嘗試'xmlDoc.responseXML' – d4rkpr1nc3 2013-03-25 14:14:32

+0

在上面的答案中,你需要在readyState ==,但除此之外它是一個贏家。 – flxa 2013-06-03 06:10:37

0

中解析XML字符串

下面的代碼片斷解析的XML字符串到XML DOM對象:

txt="<bookstore><book>"; 
txt=txt+"<title>Everyday Italian</title>"; 
txt=txt+"<author>Giada De Laurentiis</author>"; 
txt=txt+"<year>2005</year>"; 
txt=txt+"</book></bookstore>"; 

if (window.DOMParser) 
{ 
    parser=new DOMParser(); 
    xmlDoc=parser.parseFromString(txt,"text/xml"); 
} 
else // Internet Explorer 
{ 
    xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); 
    xmlDoc.async=false; 
    xmlDoc.loadXML(txt); 
} 

解析XML文檔

下面的代碼片斷解析一個XML文檔轉換成的XML DOM對象:

if (window.XMLHttpRequest) 
{ // code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
} 
else 
{ // code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
} 
xmlhttp.open("GET","books.xml",false); 
xmlhttp.send(); 
xmlDoc=xmlhttp.responseXML; 
+0

嗨,如果我去那,並使用document.write(xmlDoc.responseText)我總是得到「undefined」 – 2012-04-19 13:07:03

+0

@FabianBoulegue - 在我的代碼中有**沒有**'xmlDoc.responseText'。 – 2012-04-19 13:09:39

+0

yeahr但沒有我沒有得到一個空白頁 - 如果我只是使用您的代碼 – 2012-04-19 13:13:08

0

你既可以警報( '您的數據或文字在這裏')數據並將其顯示在彈出窗口中,或使用各種方法選擇div並使用.html(data)插入數據。