js將xml資料寫入table表格

螞蟻小編發表於2017-04-14

本章節分享一段程式碼例項,它實現了將xml中的資料寫入table表格的功能。

xml程式碼如下:

[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程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<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>

相關文章