61,129
社区成员




<!DOCTYPE html>
<html>
<head>
<title>获取XML文件的某个节点下的某些元素</title>
<meta charset="UTF-8">
<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", "Breakfast_menu.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
x = xmlDoc.getElementsByTagName("food");// x忘记写过
function displayFood(i) {
name = (x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
price = (x[i].getElementsByTagName("price")[0].childNodes[0].nodeValue);
description = (x[i].getElementsByTagName("description")[0].childNodes[0].nodeValue);
calories = (x[i].getElementsByTagName("calories")[0].childNodes[0].nodeValue);
txt = "i:" + i + "<br/>Name:" + name + "<br/>Price:" + price +
"<br/>Description:" + description + "<br/>Calories:" + calories;
document.getElementById("showFood").innerHTML = txt;// 是getElementById(),不是getElementsById()。没有s。
}
</script>
</head>
<body>
<div id="showFood">Click on a Food to display album information.</div>
<hr>
<script>
document.write("<table border='1'");
// 遍历每一个food
for (var i = 0; i < x.length; i++) {
document.write("<tr onclick= displayFood(" + i + ")>");
document.write("<td>");
document.write(i);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("price")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
document.write("params.length:" + x.length);
</script>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?><!-- 也可以是ISO-8859-1编码 -->
<!-- 该xml引用外部css样式 -->
<!-- <?xml-stylesheet type="text/css" href="./Breakfast_menu.css"?> -->
<!-- 该xml引用外部学生类样式 -->
<?xml-stylesheet type="text/xsl" href="./Breakfast_menu.xsl"?>
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waffles with plenty of real
maple syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>Light Belgian waffles covered with strawberries and
whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>Light Belgian waffles covered with an assortment of fresh
berries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>Thick slices made from our homemade sourdough bread
</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>Two eggs, bacon or sausage, toast, and our ever-popular
hash browns</description>
<calories>950</calories>
</food>
</breakfast_menu>