将Xml文件链接到HTML

时间:2015-03-17 06:06:52

标签: javascript html xml

我创建了一个简单的xml文件和一个html文件来显示xml文件的详细信息,但是它不能正常工作..在同一个文件夹中全部...

这是我的xml文件:

student.xml

        <?xml version="1.0" encoding="utf-8"?>
<Student>
<Name>Student</Name>
<Gender>Boy</Gender>
<City>Mumbai</City>
<PhoneNumbers>42607700, 42607701</PhoneNumbers>
<Email>student@aurus.com</Email>
</Student>

Html文件:

studentDetails.html

    <!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js"></script>
</head>
<body>

<script>
xmlDoc=loadXMLDoc("student.xml");

x=xmlDoc.getElementsByTagName("Student");

for (i=0;i<x.length;i++)
  { 
  document.write(x[i].childNodes[0].nodeValue);
  document.write("<br>");
  }
</script>
</body>
</html>

和Javascript文件:

loadXMLDoc.js

    function loadXMLDoc(student)
{

if (window.XMLHttpRequest)
  {
  xhttp=new XMLHttpRequest();
  }
else // code for IE5 and IE6
  {
  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

 xhttp.open("GET",student,false);
xhttp.send();
return xhttp.responseXML;
}

plz help

1 个答案:

答案 0 :(得分:0)

我为你写了一个在Firefox中运行良好但在Chrome中运行不正常的示例。我认为这是因为您在本地请求xml文件。那应该是通过服务器。

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
    border: 1px solid black;
    border-collapse:collapse;
}
th, td {
    padding: 5px;
}
</style>
</head>
<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","students.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML; 

document.write("<table><tr><th>Students</th><th>Age</th></tr>");
var x=xmlDoc.getElementsByTagName("student");
for (i=0;i<x.length;i++)
  { 
  document.write("<tr><td>");
  document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
  document.write("</td><td>");
  document.write(x[i].getElementsByTagName("age")[0].childNodes[0].nodeValue);
  document.write("</td></tr>");
  }
document.write("</table>");
</script>

</body>
</html>

students.xml

<?xml version="1.0" encoding="utf-8"?>
<STUDENTS>
    <student>
        <name>Hanzallah</name>
        <age>20</age>
        <exp>Everything</exp>
    </student>
    <student>
        <name>Afgan</name>
        <age>22</age>
        <exp>Nothing</exp>
    </student>
</STUDENTS>