【发布时间】:2014-08-09 10:47:09
【问题描述】:
我一直在搞乱一些在线脚本来解析 XML 以将其显示在表格中。不幸的是,与我看到的示例不同,我的没有显示表格。
<html>
<head>
</head>
<body>
<script>
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","europe.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.write("<table border='1'>");
var x = xmlDoc.getElementsByTagName("country");
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("users")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
</script>
</body>
</html>
这是 europe.xml
<?xml version="1.0" ?>
<continent name="Europe">
<country>
<name>Albania</name>
<users>1.6 Million</users>
</country>
<country>
<name>Austria</name>
<users>6.7 Million</users>
</country>
<country>
<name>Belgium</name>
<users>8.6 Million</users>
</country>
</continent>
【问题讨论】:
-
为什么不使用 XSLT 将 XML 转换为 XHTML?
-
正如上面提到的@DaveJarvis,如果您不打算将XML 作为现有HTML 文档的一部分 加载,而是将整个XML 转换为HTML,XSLT 绝对是最佳选择。如果遇到任何问题,您可以尝试并提出带有 XSLT 标记的问题。
标签: javascript html ajax xml