本文实例讲述了JS读取XML文件数据并以table形式显示数据的方法。分享给大家供大家参考,具体如下:
先看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>
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、火狐,其他浏览器我没试。
更多关于JavaScript相关内容可查看本站专题:《JavaScript操作XML文件技巧总结》、《JavaScript中ajax操作技巧总结》、《JavaScript中json操作技巧总结》、《JavaScript切换特效与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript动画特效与技巧汇总》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。
本文地址:https://www.stayed.cn/item/22453
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我