Parsing xml feeds with javascript

Beacon Blog Article

By Beacon News | Published October 28, 2013 | Categories: Web Development

There can be any number of reasons to parse xml. Perhaps you want to set up a custom search of an RSS feed. Maybe you need to render a data report from your ERP system on a web page but can’t get an html output from your ERP provider. Whatever the reason, parsing xml with javascript is very easy.

For simplicity we’ll include jQuery 1.5 or later. Next download and include an xml to json converter. Finally you’ll need some xml. My examples will use the following xml feed:

<first_name>Frank
<last_name>Sinatra
  
  
<first_name>Sammy
<last_name>Davis Jr.
  
  
<first_name>Dean
<last_name>Martin

We’ll say my xml is hosted at www.mydomain.com/musicians.xml. In order to search this file you’ll first pull the file into scope with a jQuery get request like this:

jQuery.get("www.mydomain.com/musicians.xml", function (data) { ... });

That will pass the xml from the file requested as a parameter to the callback function which can be defined either inline as in the example above or as a standalone function for a more modular approach. Inside the callback you’ll need to convert the xml into a json object for easy manipulation. This is done via the following line of code:

var json = jQuery.xml2json(data);

At this point the rest is very straight-forward. The xml is now in a json object and can be accessed by the following ways:

json.artist;// =&gt; will give the collection of artists, in this case, all three artists.
json.artist[1].first_name;// =&gt; "Sammy", or the first_name node value for the second artist in the collection (javascript arrays are 0 based)
Now you have access to all the data in the xml as a single object making data retrieval very simple, even for complex xml data feeds like RSS.

Let's get to work!

Contact Us