XML元素没有显示在HTML页面中?

时间:2013-12-14 15:44:52

标签: html css xml dom xslt

我遇到了一些问题。我已经开始创建一个HTML页面,并为我的XML提供了一个单独的文档,我需要将XML中的某些元素显示到HTML页面中。我一直在W3学校并使用以下代码并尝试将其操作到我的HTML页面

<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js"></script>
</head>
<body>
<script>
  xmlDoc=loadXMLDoc("books.xml");

  document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue + "<br>");
  document.write(xmlDoc.getElementsByTagName("author")[0].childNodes[0].nodeValue + "<br>");
  document.write(xmlDoc.getElementsByTagName("year")[0].childNodes[0].nodeValue);
</script>
</body>
</html>

然而,我得到的只是我用HTML制作的,而不是关于XML的。我严格按照上面的代码创建了另一个文档,我得到的只是一个白页。我已经尝试过Internet Explorer和chrome。与W3学校的联系是:

http://www.w3schools.com/dom/tryit.asp?filename=try_dom_parsertest

请帮忙吗?

1 个答案:

答案 0 :(得分:0)

我稍微调整了你的代码,以下工作。我从我认为你正在使用的w3s教程中获取它。我想你可以安全地删除IE5 / 6特定代码!

<!DOCTYPE html>
<html>
<head>
<script>
if (window.XMLHttpRequest)
  {
  xhttp=new XMLHttpRequest();
  }
else // IE 5/6
  {
  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xhttp.open("GET","books.xml",false);
xhttp.send();
xmlDoc=xhttp.responseXML;
</script>
</head>
<body>
<script>
  document.write(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue + "<br>");
  document.write(xmlDoc.getElementsByTagName("author")[0].childNodes[0].nodeValue + "<br>");
  document.write(xmlDoc.getElementsByTagName("year")[0].childNodes[0].nodeValue);
</script>
</body>
</html>

我在这里假设您的books.xml文件就在这里 http://www.w3schools.com/dom/books.xml

一个警告 - 只有通过网络服务器查看它才有效 - 因此您需要在自己的PC上使用开发服务器或将其上传到某个地方,如果您直接在浏览器中打开它将无法使用。

值得我推荐XSLT来处理XML http://www.w3schools.com/xml/xml_xsl.asp