简体   繁体   中英

Regarding parsing of XML by DOM

I am learning XML from www.w3schools.com. 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. Can anyone please let me know if I have missed something.

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

<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. Also I am using chrome browser. When I run the html file I am not able to see the content of XML file. 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. Kindly help.

It must be having a problem finding the xml file, I would double check the name and casing. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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