javascript解析xml檔案。相容IE、firefox、Chrome

來源:互聯網
上載者:User

.html
<div id="bookList" style="width:500px;">
<script language="javascript">
loadXML = function(fileRoute){
    xmlDoc=null;
     if (window.ActiveXObject){
        xmlDoc = new ActiveXObject('Msxml2.DOMDocument');
        xmlDoc.async=false;
        xmlDoc.load(fileRoute);
    }
    else if (document.implementation && document.implementation.createDocument){
        var xmlhttp = new window.XMLHttpRequest();
        xmlhttp.open("GET",fileRoute,false);
        xmlhttp.send(null);
        var xmlDoc = xmlhttp.responseXML.documentElement;
    }
    else {xmlDoc=null;}
    return xmlDoc;
}
var xmlDoc=loadXML('books.xml');

var cNodes = xmlDoc.getElementsByTagName("book"); //alert(cNodes.length)
var msg='<table border="1" cellspacing="0" cellpadding="0" width="500">';
msg+='<tr><td width="90"></td><td width="100">圖書編號</td><td width="100">種類編號</td><td width="110">圖書名稱</td><td width="100">作者</td></tr>';
for(j=0;j<cNodes.length;j++)
{
    var bookID=xmlDoc.getElementsByTagName("book")[j].getAttribute("id");
    var sortID=xmlDoc.getElementsByTagName("book")[j].getAttribute("sortID");
    var bookTitle=xmlDoc.getElementsByTagName("title")[j].childNodes[0].nodeValue;
    var bookAuthor=xmlDoc.getElementsByTagName("author")[j].childNodes[0].nodeValue;
    msg+='<tr><td>'+(j+1)+'</td><td>'+bookID+'</td><td width="100">'+sortID+'</td><td width="190">'+bookTitle+'</td><td width="120">'+bookAuthor+'</td></tr>'
}
msg+='</table>';
document.getElementById("bookList").innerHTML=msg;
</script>

.xml
<?xml version="1.0" encoding="gb2312"?>
<books>
<book id="4" sortID="a4">
<title>author4aa</title>
<author>author4</author>
</book>
<book id="5" sortID="a5">
<title>author55</title>
<author>author5</author>
</book>
<book id="6" sortID="a6">
<title>booktitle</title>
<author>author6</author>
</book>
<book id="7" sortID="a7">
<title>booktitle</title>
<author>author7</author>
</book>
</books>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.