Amitav Roy

Blog on web and travel

Working with XML in Angular JS

Posted on 4 Aug 2013 by Amitav Roy

Working with XML in Angular JS

In this tutorial I will show you how to use the X2JS javascript library to parse XML and turn that into an AngularJS object. This is one of my RND project where I am using XML files along with HTML to create an e-learning shell.


In this tutorial I have a courseDef xml file which has the module structure. The navigation tree decides the chapters and it’s pages. To keep it simple, I have taken only two chapters with a few pages inside them. And most important which is conversion of XML into JS object is done by the X2JS library. You can download it here.

The Controller

In this controller I have three pages defined – the main index page, the home page which is the default router for Angular and the last one is where I am showing the chapter information.

You can also find the file here: View file

The XML file

The XML file is structured as course. Inside it is my navigation. It contains chapters which has pages inside the. The idea is to pick up the html file name from the page tags and render the screens accordingly.

The Angular app

Now comes the main part – the angular code. First I have declared the routes. I have two for now, the home which shows the chapters in the course and the second one to show the pages inside an individual chapter using routeParams.

Currently I have kept the code very simple and so all the $http gets are inside the controller. But in my subsequent tutorials I will have to convert them into factory methods because right now I am loading the same XML every time I change the controller which is a bad thing to do from performance point of view.

There are two controllers – the MainCtrl which is being used by the home page. It is fetching the XML file using $http get and then I am using the “xml_str2json” function to parse the XML data from string to javascript object.

Once that is done, I push each chapter and finally assign that to scope so that inside the HTML I can display it.

Even in the second controller, which is the chapterCtrl I have written almost the same code, except that here I am taking an individual chapter and looping it’s inner pages through the parameter which is passed as chapter id.

You can also find the file here: View file

If you see, the home page now shows two chapters and if you click on an individual chapter it will take you to the chapter’s details page and show you the screen inside it.