站长网(Downzz.com)
站长网(Downzz.com)
当前位置:首页 > 站长教程 > 建站经验 > JS教程
js将xml数据写入table表格_JS实例
时间:2019-10-26 23:44:04 围观:222 来源:Downzz

本章节分享一段代码实例,它实现了将xml中的数据写入table表格的功能。

xml代码如下:

<?xml version="1.0" standalone="yes"?>
<student>
 <stuinfo>
  <stuName>Downzz.com一</stuName>
  <stuSex>男</stuSex>
  <stuAge>18</stuAge>
 </stuinfo>
 <stuinfo>
  <stuName>Downzz.com二</stuName>
  <stuSex>男</stuSex>
  <stuAge>31</stuAge>
 </stuinfo>
 <stuinfo>
  <stuName>Downzz.com三</stuName>
  <stuSex>男</stuSex>
  <stuAge>22</stuAge>
 </stuinfo>
 <stuinfo>
  <stuName>Downzz.com四</stuName>
  <stuSex>女</stuSex>
  <stuAge>25</stuAge>
 </stuinfo>
 <stuinfo>
  <stuName>Downzz.com五</stuName>
  <stuSex>男  </stuSex>
  <stuAge>32</stuAge>
 </stuinfo>
 <stuinfo>
  <stuName>Downzz.com六</stuName>
  <stuSex>男</stuSex>
  <stuAge>28</stuAge>
 </stuinfo>
 <stuinfo>
  <stuName>Downzz.com七</stuName>
  <stuSex>女</stuSex>
  <stuAge>23</stuAge>
 </stuinfo>
 <stuinfo>
  <stuName>Downzz.com八</stuName>
  <stuSex>女</stuSex>
  <stuAge>22</stuAge>
 </stuinfo>
</student>

js代码如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.downzz.com/" />
<title>Downzz.com</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>

文章为作者独立观点不代表本网立场,未经允许不得转载。