简体   繁体   English

关于通过DOM解析XML

[英]Regarding parsing of XML by DOM

I am learning XML from www.w3schools.com. 我正在从www.w3schools.com学习XML。 I am trying to simulate one of their example where I need to parse the XML file but I am not able to get the desired result. 我试图模拟其中的一个示例,在该示例中我需要解析XML文件,但无法获得所需的结果。 Can anyone please let me know if I have missed something. 有人可以让我知道是否错过了什么。

note.xml note.xml

<?xml version="1.0" encoding="UTF-8"?>
<note><to>Tove</to><from>Jani</from><heading>Reminder
</heading><body>Don't forget me this weekend!</body></note>

blabla.html blabla.html

<html>
<body>
<h1>W3Schools Internal Note</h1>
<div>
<b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span>
</div>

<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","note.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
</script>

</body>
</html>

PS: I have saved the xml file and the .html file at the same location in my laptop. PS:我已经将xml文件和.html文件保存在笔记本电脑的同一位置。 Also I am using chrome browser. 另外我正在使用Chrome浏览器。 When I run the html file I am not able to see the content of XML file. 运行html文件时,看不到XML文件的内容。 Above code is exact copy of what is given on the web site. 上面的代码是网站上给出的内容的精确副本。 I think I am missing some minor point here and which is causing the XML to not get parsed. 我想我在这里遗漏了一些小问题,这导致XML无法解析。 Kindly help. 请帮助。

It must be having a problem finding the xml file, I would double check the name and casing. 查找xml文件肯定有问题,我会仔细检查名称和大小写。 Also permissions of folders could sometimes be an issue, but if they are in the same folder, I can't imagine that causeing you grief. 文件夹的权限有时也可能是一个问题,但是如果它们位于同一文件夹中,我无法想象这会引起您的悲伤。

Your code seems to work fine. 您的代码似乎可以正常工作。 This plunker is virtually a copy of the code you have, so we know the code works! 插件实际上是您拥有的代码的副本,因此我们知道该代码有效! Except I changed the name of the .xml to "test", which shouldn't change anything. 除非我将.xml的名称更改为“ test”,否则不应进行任何更改。

xmlhttp.open("GET","test.xml",false);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM