适用于各种浏览器的XML解析方法

来源:互联网 发布:印巴分治 知乎话题 编辑:程序博客网 时间:2024/05/29 06:47

 

  1. <div id="bookList" style="width:500px;">
  2. <script language="javascript">
  3. loadXML = function(fileRoute)
  4. {
  5.     xmlDoc = null;
  6.     if (window.ActiveXObject)
  7.     {
  8.         xmlDoc = new ActiveXObject('Msxml2.DOMDocument');
  9.         xmlDoc.async = false;
  10.         xmlDoc.load(fileRoute);
  11.     }
  12.     else if (document.implementation && document.implementation.createDocument)
  13.     {
  14.         var xmlhttp = new window.XMLHttpRequest();
  15.         xmlhttp.open("GET",fileRoute,false);
  16.         xmlhttp.send(null);
  17.         var xmlDoc = xmlhttp.responseXML.documentElement; 
  18.     }
  19.     else 
  20.     {
  21.         xmlDoc = null;
  22.     }
  23.     return xmlDoc;
  24. }
  25. var xmlDoc = loadXML('books.xml');
  26. var cNodes = xmlDoc.getElementsByTagName("book"); //alert(cNodes.length)
  27. var msg = '<table border="1" cellspacing="0" cellpadding="0" width="500">';
  28. msg += '<tr>'
  29.     +  '<td width="90"></td>'
  30.     +  '<td width="100">图书编号</td>'
  31.     +  '<td width="100">种类编号</td>'
  32.     +  '<td width="110">图书名称</td>'
  33.     +  '<td width="100">作者</td>'
  34.     +  '</tr>';
  35. for(j=0;j<cNodes.length;j++)
  36. {
  37.     var bookID = xmlDoc.getElementsByTagName("book")[j].getAttribute("id");
  38.     var sortID = xmlDoc.getElementsByTagName("book")[j].getAttribute("sortID");
  39.     var bookTitle = xmlDoc.getElementsByTagName("title")[j].childNodes[0].nodeValue;
  40.     var bookAuthor = xmlDoc.getElementsByTagName("author")[j].childNodes[0].nodeValue;
  41.     msg += '<tr>'
  42.                 + '<td>'+(j+1)+'</td>'
  43.                 + '<td>' + bookID + '</td>' 
  44.                 + '<td width="100">' + sortID + '</td>'
  45.                 + '<td width="190">' + bookTitle + '</td>'
  46.                 + '<td width="120">' + bookAuthor+'</td>'
  47.         + '</tr>';
  48. }
  49. msg += '</table>';
  50. document.getElementById("bookList").innerHTML=msg;
  51. </script>
  1. <?xml version="1.0" encoding="gb2312"?>
  2. <books>
  3.     <book id="4" sortID="a4">
  4.         <title>author4aa</title>
  5.         <author>author4</author>
  6.     </book>
  7.     <book id="5" sortID="a5">
  8.         <title>author55</title>
  9.         <author>author5</author>
  10.     </book>
  11.     <book id="6" sortID="a6">
  12.         <title>booktitle</title>
  13.         <author>author6</author>
  14.     </book>
  15.     <book id="7" sortID="a7">
  16.         <title>booktitle</title>
  17.         <author>author7</author>
  18.     </book>
  19. </books>

 

 

原创粉丝点击