28 10, 2013

Parsing xml feeds with javascript

By | 2016-11-22T09:52:31+00:00 October 28th, 2013|Categories: Web Development|Tags: , , , |

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.

To start you’ll need three things. For simplicity we’ll include jQuery 1.5 or later. Next download and include this xml to json converter: http://www.fyneworks.com/jquery/xml-to-json/. Finally you’ll need some xml. My examples will use the following xml feed:

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:

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:

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:

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.