使用JavaScript解析XML文件
我不熟悉堆栈溢出和一般的编码。我正在尝试获取一个XML文件,并使用JavaScript在浏览器中呈现它。我查看了一些如何执行此操作的示例代码,并得出了以下代码:使用JavaScript解析XML文件,javascript,xml,Javascript,Xml,我不熟悉堆栈溢出和一般的编码。我正在尝试获取一个XML文件,并使用JavaScript在浏览器中呈现它。我查看了一些如何执行此操作的示例代码,并得出了以下代码: <!DOCTYPE html> <html> <body> <script> if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpReque
<!DOCTYPE html>
<html>
<body>
<script>
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","social.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("CD");
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("c_id")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("facebook_id")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
</script>
</body>
</html>
if(window.XMLHttpRequest)
{//IE7+、Firefox、Chrome、Opera、Safari的代码
xmlhttp=新的XMLHttpRequest();
}
其他的
{//IE6、IE5的代码
xmlhttp=新的ActiveXObject(“Microsoft.xmlhttp”);
}
open(“GET”,“social.xml”,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
文件。填写(“”);
var x=xmlDoc.getElementsByTagName(“CD”);
对于(i=0;i,您需要在发送请求之前向xmlhttprequest
添加一个onload
事件侦听器。此外,您可能需要使用DOMParser
解析XML。无论如何,这在现代浏览器上应该可以工作:
<!DOCTYPE html>
<html>
<body>
<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onload = function() {
var xmlDoc = new DOMParser().parseFromString(xmlhttp.responseText,'text/xml');
console.log(xmlDoc);
document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("CD");
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("c_id")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("facebook_id")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
}
xmlhttp.open("GET","social.xml",false);
xmlhttp.send();
</script>
</body>
</html>
if(window.XMLHttpRequest)
{//IE7+、Firefox、Chrome、Opera、Safari的代码
xmlhttp=新的XMLHttpRequest();
}
其他的
{//IE6、IE5的代码
xmlhttp=新的ActiveXObject(“Microsoft.xmlhttp”);
}
xmlhttp.onload=函数(){
var xmlDoc=new DOMParser().parseFromString(xmlhttp.responseText,'text/xml');
console.log(xmlDoc);
文件。填写(“”);
var x=xmlDoc.getElementsByTagName(“CD”);
对于(i=0;i)您使用哪个浏览器来测试此问题?它是否报告任何错误?