Parse XML with jQuery
by Thai on March 14, 2010
This little snippet will parse XML and format any way you like. It’s as simple as using jQuery’s .each() method and then appending it to a div. If you’re trying to parse a RSS feed then I suggest using jFeed.
$(document).ready(function(){
$.ajax({
type: "GET",
url: "info.xml",
dataType: "xml",
success: parseXML
});
function parseXML(xml){
//find "book" nodes and use jQuery’s for each method to get strings
$(xml).find("book").each(function(){
//store nodes in vars
var title = $(this).find("title");
var author = $(this).find("author");
var isbn = $(this).attr("isbn");
//add the strings in the output div
$("#output").append(title.text() + "<br />");
$("#output").append(author.text() + "<br />");
$("#output").append(isbn + "<br />");
});
}
});
$.ajax({
type: "GET",
url: "info.xml",
dataType: "xml",
success: parseXML
});
function parseXML(xml){
//find "book" nodes and use jQuery’s for each method to get strings
$(xml).find("book").each(function(){
//store nodes in vars
var title = $(this).find("title");
var author = $(this).find("author");
var isbn = $(this).attr("isbn");
//add the strings in the output div
$("#output").append(title.text() + "<br />");
$("#output").append(author.text() + "<br />");
$("#output").append(isbn + "<br />");
});
}
});
These are books that I’ve read over and over so I recommend them.
<?xml version="1.0" encoding="utf-8"?>
<library>
<book isbn="0765347415">
<title>Terminator vs Godzilla</title>
<author>John Connor</author>
<published>1/13/2009</published>
</book>
<book isbn="0983746513">
<title>Olives and Beer</title>
<author>Long Dong</author>
<published>12/28/2010</published>
</book>
<book isbn="0037616351">
<title>Froyo</title>
<author>Tutti Frutti</author>
<published>3/13/2010</published>
</book>
</library>
<library>
<book isbn="0765347415">
<title>Terminator vs Godzilla</title>
<author>John Connor</author>
<published>1/13/2009</published>
</book>
<book isbn="0983746513">
<title>Olives and Beer</title>
<author>Long Dong</author>
<published>12/28/2010</published>
</book>
<book isbn="0037616351">
<title>Froyo</title>
<author>Tutti Frutti</author>
<published>3/13/2010</published>
</book>
</library>
Leave your comment