简体   繁体   中英

Parsing XML data using Javascript

I have gone through the basics in xml and now trying to parse xml data using javascript. I have taken help from w3schools & written the following code but parsing is not happening and a blank page is getting displayed. Please help...

The xml file am using is books.xml :

<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>

The Html code is:

<!DOCTYPE html>
<html>
<head>
<script>

function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
  {
  xhttp=new XMLHttpRequest();
  }

xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}


</script>
</head>
<body>
<script>

var xmlDoc=loadXMLDoc("C:/Users/A/Desktop/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>

I've tried your code, it works (I'm using Mozilla Firefox 28 on Mac OSX).

Remember that on Windows systems the directory separator is a backslash \\ and NOT a slash / Try to change that in your xml path. Maybe you see a blank page because you didn't provide a fallback in case your ajax request cannot find that xml. If you're using Firebug you should see a "404 Not Found" error when trying to GET that xml.

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