使用JavaScript解析XML文件

问题描述:

我是Stack OverFlow和一般编码的新手。我正在尝试使用JavaScript将XML文件呈现在浏览器中。我已经在如何做到这一点一些示例代码环顾四周,用下面的代码上来:使用JavaScript解析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.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> 

无论如何,当我在我的本地服务器没有,我想在显示的数据中运行这个表出现。我的.html文件和.xml文件位于同一个文件夹中,所以我相信我有正确的文件路径。我可能只是在这里犯了一个菜鸟错误,但是我不能为了我的生活找出为什么没有创建列出c_id和facebook_id值的表。我四处寻找答案,一直没有找到答案。任何帮助将不胜感激。谢谢!

+0

你使用的是什么浏览器测试呢?它是否报告任何错误? –

在发送请求之前,您需要将onload事件侦听器添加到xmlhttprequest。另外,您可能需要使用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> 

现在,只需一两件事情值得一提的你在做什么:

  • xmlhttprequest对象都意味着不同的许多不同的参数东西:readystate,状态码,作品。你可能会从中受益更多。

  • document.write应该永远不会被使用,永远。事实上,任何HTML注入手段都应该非常小心地处理。如果你想:)你可以使用在许多MVC式的框架,共同基于模板的解决方案,或mine