js将xml数据写入table表格
分类:实例代码
本章节分享一段代码实例,它实现了将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>
js代码如下:
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <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"> <div> <input type="button" value="JS读取XML" onclick="ReadXml()" /><br /> <div id="xmlMsg"> </div> </div> </form> </body> </html>
js将xml数据写入table表格,这样的场景在实际项目中还是用的比较多的,关于js将xml数据写入table表格就介绍到这了。
js将xml数据写入table表格属于前端实例代码,有关更多实例代码大家可以查看。