Esküvő

Reading XML with jQuery

A few days ago I found a brilliant script at Think2Loud about how to read XML data and show it in HTML with jQuery.

XML file

Save this as sites.xml.

<?xml version="1.0" encoding="iso-8859-1"?>
 <sites>
   <site id="1">
     <title>Think2Loud</title>
	<url>http://www.think2loud.com</url>
     <desc>
       <brief>this is the brief description.</brief>
       <long>...and this is the long description.  See how long it is :)</long>
     </desc>
   </site>
   <site id="2">
     <title>jaredharbour.com</title>
	<url>http://www.jaredharbour.com</url>
     <desc>
       <brief>this is the brief description.</brief>
       <long>...and this is the long description.  See how long it is :)</long>
     </desc>
   </site>
   <site id="3">
     <title>Css Tricks</title>
	<url>http://www.css-tricks.com</url>
     <desc>
       <brief>this is the brief description.</brief>
       <long>...and this is the long description.  See how long it is :)</long>
     </desc>
   </site>
 </sites>

jQuery

Insert this code to your HTML.

<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
	$.ajax({
		type: "GET",
		url: "sites.xml",
		dataType: "xml",
		success: function(xml) {
			$(xml).find('site').each(function(){
				var id = $(this).attr('id');
				var title = $(this).find('title').text();
				var url = $(this).find('url').text();
				$('<div class="items" id="link_'+id+'"></div>').html('<a href="'+url+'">'+title+'</a>').appendTo('#page-wrap');
				$(this).find('desc').each(function(){
					var brief = $(this).find('brief').text();
					var long = $(this).find('long').text();
					$('<div class="brief"></div>').html(brief).appendTo('#link_'+id);
					$('<div class="long"></div>').html(long).appendTo('#link_'+id);
				});
			});
		}
	});
});
</script>

HTML markup

<div id="page-wrap">
 <h1>Reading XML with jQuery</h1>
</div>

Download the source code form Think2Loud.

Enjoy!


Esküvő


Related articles

Pie Chart with Flot jQuery Plugin

Pie Chart with Flot jQuery Plugin

28/02/2013

Learn how to use the pie plugin for Flot charts.

Draw Graph with Flot jQuery Chart

Draw Graph with Flot jQuery Chart

26/02/2013

Flot is a brilliant jQuery Graph drawning plugin developed by Ole Laursen and David Schnur.

jQuery Tagging Plugin

jQuery Tagging Plugin

24/02/2013

This plugin transforms an HTML unordered list into a unique tags list and also uses jQuery UI auto-complete to supply suggestions to users as they type.


Leave a comment

We welcome any comment from you! Please keep in mind that comments are moderated and rel='nofollow' is in use. So, please do not use a domain as your name or a spammy keyword, or your comment will be deleted.

Name: *

E-mail: *

Message: *

Click on the lion *


Find us on Facebook

Tags

Esküvő

Back to Top