日期:2014-05-16  浏览次数:20363 次

javascript如何访问一个多记录的XML文档
javascript如何访问一个多记录的XML文档,同时一条记录有多个字段内容.
就像一张表有多行,每行有多个字段一样,XML文档内容会是什么样的,如果用JS读取,希望能给我帮助谢谢!

多行的记录是可变的,因为这部分我要在服务端生成

------解决方案--------------------
<html>
<head>
<meta http-equiv= "Content-Type " content= "text/html; charset=gb2312 ">
<title> 创建表格(数据从xml文件中读取) </title>
<script language= "javascript ">
function loadXML(handler)
{
var url = "../xml/employees.xml ";
if(document.implementation && document.implementation.createDocument)
{
var xmldoc = document.implementation.createDocument( " ", " ", null);
xmldoc.onload = handler(xmldoc, url);
xmldoc.load(url);
}
else if(window.ActiveXObject)
{
var xmldoc = new ActiveXObject( "Microsoft.XMLDOM ");
xmldoc.onreadystatechange = function()
{
if(xmldoc.readyState == 4) handler(xmldoc, url);
}
xmldoc.load(url);
}
}
function makeTable(xmldoc, url)
{
var table = document.createElement( "table ");
table.setAttribute( "border ", "1 ");
table.setAttribute( "cellSpacing ", "1 ");
table.setAttribute( "width ", "600 ");
table.setAttribute( "class ", "tab-content ");
document.body.appendChild(table);
var caption = "Employee Data from " + url;
table.createCaption().appendChild(document.createTextNode(caption));
var header = table.createTHead();
var headerrow = header.insertRow(0);
headerrow.insertCell(0).appendChild(document.createTextNode( "姓名 "));
headerrow.insertCell(1).appendChild(document.createTextNode( "职业 "));
headerrow.insertCell(2).appendChild(document.createTextNode( "工资 "));
var employees = xmldoc.getElementsByTagName( "employee ");
for(var i=0;i <employees.length;i++)
{
var e = employees[i];
var name = e.getAttribute( "name ");
var job = e.getElementsByTagName( "job ")[0].firstChild.data;
var salary = e.getElementsByTagName( "salary ")[0].firstChild.data;
var row = table.insertRow(i+1);
row.insertCell(0).appendChild(document.createTextNode(name));
row.insertCell(1).appendChild(document.createTextNode(job));
row.insertCell(2).appendChild(document.createTextNode(salary));
}
}
</script>
<link href= "css/style.css " rel= "stylesheet " type= "text/css ">
</head>

<body onLoad= "loadXML(makeTable) ">
</body>
</html>

employees.xml
<?xml version= "1.0 " encoding= "gb2312 "?>
<employees>
<employee name= "J.Doe ">
<job> Programmer </job>
<salary> 32768 </salary>
</employee>
<employee name= "A.Baker ">
<job> Sales </job>
<salary> 70000 </salary>
</employee>
<employee name= "Big Cheese ">
<job> CEO </job>
<salary> 100000 </salary>
</employee>
</employees>
------解决方案--------------------
<html>
<head>
<script language= "javascript ">

var i = -1;
var orderDoc = new ActiveXObject( "MSXML2.DOMDocume