Archive for December, 2010

Using jquery to parse XML

Thursday, December 9th, 2010

I have used javascript to parse XML in the past but jquery is by far, the easiest and most flexible solution. You would not need any plug-ins except for the jquery library which can be found here.

In your html file, you would need a placeholder for where the parsed XML would appear:


<div class="xml-text"></div>

The sample xml file looks a little like this:

<?xml version="1.0" encoding="UTF-8"?>
<xmlcontent>
<article>
<content>
<para>This is the first paragraph of the first article</para>
<para>This is the second paragraph of the first article.</para>
</content>
</article>
<article>
<content>
<para>This is the first paragraph of the second article.</para>
<para>This is the second paragraph of the second article.</para>
<para>This is the third paragarph of the second article.</para>
</content>
</article>
<footer>
<content>
<para>© 2010. All Rights Reserved.</para>
<para>Contact the webmaster for any questions, comments and/or suggestions.</para>
</content>
</footer>
</xmlcontent>

At the bottom of your html, insert this piece of script:


<script type="text/javascript">
<!--
$(document).ready(function () {
$.ajax({
type: "GET",
url: "xml_file.xml",
dataType: "xml",
success: xmlParse
});
});

function xmlParse(xml) {
$(xml).find("article").each(function () {
$(this).find("para").each(function(){
$(".xml-text").append('

' + $(this).text() + '

 

');
});
});
}
//-->
</script>

The first line of code just initializes jquery to load the xml file . . . under url, you would need to type in your xml file – due to certain security restrictions this should be a local file – if it is an external xml feed, you would need to talk to your systems administrator or write a script to capture the xml and save it to a local directory – if your hosting provider supports PHP – then you should insert this code into rss.php


<?php
header('Content-type: application/xml'); //Changes the format from plain text to XML
echo file_get_contents($_GET['feed_url']); //Echos the RSS feed from the GET feed address
?>

And in your jquery, instead of the initialization code, you would put in this one-liner:


$.get('/rss.php',{feed_url:'http://sample.com/feed/'});

I have not fully tested grabbing external feeds, so if the code above doesn’t work, don’t blame me – but it does require a bit more work to get external feeds to work – it all depends on how your site and servers are configured.

The parse function is pretty straightforward . . . it goes through the xml content to find the <article> tag and then under each <article>, it would look for the <para> tag and then insert the text into the placeholder, which in this example is <div class=”xml-text”>. Magic!