Simple XML to HTML table using jQuery

I am sure there are better ways, but this is one way I found works, and thought I’d take a note myself. This blog post titled “Reading XML with jQuery” from think2loud.com tutorial with downloadable source code was super helpful. In fact now that I look at it, I am basically just using his work. Another tutorial that I found helpful is this one: Tutorial: From PHP to XML to jQuery and Ajax. Anyway, I thought I would pass along, and keep it here for when I need it again…

Say you have xml file like this one, which can easily be created by Creativyst CSV to XML Converter (one of my absolutely favorite web tools of all-time)

<document>
 <row>
  <Col0>1</Col0 >
  <Col1>2</Col1 >
  <Col2>3</Col2 >
 </row>
 <row>
  <Col0>2</Col0 >
  <Col1>4</Col1 >
  <Col2>5</Col2 >
 </row>
</document>

Use this JavaScript:

$(document).ready(function(){
 $.ajax({
  type: "GET",
  url: "example.xml",
  dataType: "xml",
  success: function(xml) {
   $(xml).find('row').each(function(){
    var Col0 = $(this).find('Col0').text();
    var Col1 = $(this).find('Col1').text();
    var Col2 = $(this).find('Col2').text();
    $('<tr></tr>').html('<th>'+Col0+'</th><td>$'+Col1+'</td><td>$'+Col2+'</td>').appendTo('#chart');
   });
  }
 });
});

And have this html:


<table id="chart">
  <tr><td></td><th>Data header 1</th><th>Data header 2</th></tr>
</table>

4 Responses to “Simple XML to HTML table using jQuery”

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">