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表格属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容