2012-04-19 83 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)插入数据。