JS读取XML文件数据并以table显示数据(兼容IE火狐)

先看xml文件:

<?xml version="1.0" standalone="yes"?>
<student>
  <stuinfo>
    <stuName>张秋丽</stuName>
    <stuSex></stuSex>
    <stuAge>18</stuAge>
  </stuinfo>
  <stuinfo>
    <stuName>李文才</stuName>
    <stuSex></stuSex>
    <stuAge>31</stuAge>
  </stuinfo>
  <stuinfo>
    <stuName>李斯文</stuName>
    <stuSex></stuSex>
    <stuAge>22</stuAge>
  </stuinfo>
  <stuinfo>
    <stuName>马英</stuName>
    <stuSex></stuSex>
    <stuAge>25</stuAge>
  </stuinfo>
  <stuinfo>
    <stuName>孙红雷</stuName>
    <stuSex></stuSex>
    <stuAge>32</stuAge>
  </stuinfo>
  <stuinfo>
    <stuName>欧阳俊雄</stuName>
    <stuSex></stuSex>
    <stuAge>28</stuAge>
  </stuinfo>
  <stuinfo>
    <stuName>江琳</stuName>
    <stuSex></stuSex>
    <stuAge>23</stuAge>
  </stuinfo>
  <stuinfo>
    <stuName>小小</stuName>
    <stuSex></stuSex>
    <stuAge>22</stuAge>
  </stuinfo>
</student>
View Code

aspx页面代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="获取数据库数据生成XML.aspx.cs" Inherits="Chapter1.获取数据库数据生成XML" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function loadXMLDoc(dname) {
            if (window.XMLHttpRequest) {
                xhttp = new XMLHttpRequest();
            }
            else {
                xhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xhttp.open("GET", dname, false);
            xhttp.send("");
            return xhttp.responseXML;
        }
        function ReadXml() {
            var xmldoc = loadXMLDoc("Student.xml");
            //获得指定节点
            var divmsg = document.getElementById("xmlMsg");
            var msg = "<table border=‘1‘ id=‘mytable‘><tr><th>姓名</th><th>性别</th><th>年龄</th><tr>";
            var nodes = xmldoc.getElementsByTagName("stuinfo");
            for (var i = 0; i < nodes.length; i++) {
                msg += "<tr>";
                msg += "<td>" + nodes[i].getElementsByTagName("stuName")[0].firstChild.nodeValue + "</td>";
                msg += "<td>" + nodes[i].getElementsByTagName("stuSex")[0].firstChild.nodeValue + "</td>";
                msg += "<td>" + nodes[i].getElementsByTagName("stuAge")[0].firstChild.nodeValue + "</td>";
                msg += "</tr>";
            }
            msg += "</table>";
            divmsg.innerHTML = msg;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="JS读取XML" onclick="ReadXml()" /><br />
        <div id="xmlMsg">
        </div>
    </div>
    </form>
</body>
</html>

上面的JS操作主要就避免了使用childNodes(因为火狐中childNodes[0]获取到的是"\n"而不是我们想要的第一个子节点,这个自己可以去试下,反正我是遇到了这种情况),使得可以兼容IE、火狐,其他浏览器我没试。

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。