最近学习了xml,为了完成老师布置的大作业,可真的是......
有两种方法,一种是js解析,第二种是用数据岛
先贴上xml文件,这里是contact.xml,这个文件是我用Java代码,通过手动在控制台输入节点名称,最后创建的,具体数据并没有经过验证
<?xml version="1.0" encoding="utf-8"?>
<contactList>
<contact id="001">
<name>张三</name>
<sex>女</sex>
<age>21</age>
<phone>11111111111</phone>
<email>111111@qq.com</email>
<qq>235346662</qq>
</contact>
<contact id="002">
<name>李四</name>
<sex>男</sex>
<age>21</age>
<phone>13455555</phone>
<email>454444@qq.com</email>
<qq>235346662</qq>
</contact>
<contact id="003">
<name>王五</name>
<sex>男</sex>
<age>21</age>
<phone>13455555</phone>
<email>454444@qq.com</email>
<qq>235346662</qq>
</contact>
<contact id="004">
<name>赵六</name>
<sex>男</sex>
<age>21</age>
<phone>13455555</phone>
<email>454444@qq.com</email>
<qq>235346662</qq>
</contact>
</contactList>
这是html文件,名字可以随便取啦
获取节点名称
document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
获得属性名称,类似获取容器里面的属性
document.write(x[i].getAttribute("id"));
完整代码
<html>
<body>
<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","contact.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("contact");
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].getAttribute("id"));
document.write("</td><td>");
document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("sex")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("age")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("phone")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("email")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("qq")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
</script>
</body>
</html>
第二种方法稍后我会继续整理的,请看下一篇文章