How would I get an xml document from a particular url in javascript then look up a particular sub node and get the value?
views:
23answers:
2You can use XMLHttpRequest
to make an AJAX call to the url, as long as it's on the same domain (AJAX has same-origin policy). Also, take a look here for some tips on manipulating XML in Javascript.
If you are using jQuery, you can use jQuery.ajax
and set the datatype to XML
.
If your XML resides on another URL (i.e., not on your domain), then things get trickier. You'll need to use something server-side (like PHP, ASP, or JSP's) that generates a Javascript file that contains the XML (which it grabs from the URL) stored in a string. Then, in your page you'll need a script tag that points to this Javascript file.
Using jQuery it's really easy because you an 'query' the XML document like you would with an X/HTML document.
Let's say you had a simple xml document like this...
<book>
<title>Catcher in the Rye</title>
<author>J.D. Salinger</author>
</book>
You can use jQuery to load the document and parse out particular nodes.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.get("/book.xml", function(responseXml) {
var xml = $(responseXml);
var title = $("title", xml).text();
var author = $("author", xml).text();
alert(title); // >> Catcher in the Rye
alert(author); // >> J.D. Salinger
});
});
</script>
</head>
<body>
</body>
</html>