javascript解析xml文件。兼容IE、firefox、Chrome

.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>

你可能感兴趣的:(javascript解析xml文件。兼容IE、firefox、Chrome)