Working with xml2json Strings in Ionic Framework Project - Clearly Innovative | Web and Mobile DevelopmentClearly Innovative | Web and Mobile Development


When working on sample Ionic Framework app, BikeNearMe, for up coming workshop I needed to manipulate REST API responses. (See Project here)

As we all know, JSON is the best for an API to return, but sometimes it just doesn’t happen that way. When working with the Capital Bikeshare data, the only way to get the station update feed is to use the XML response.

To convert my data within my application I decided to use the xml2json.js library for simple conversion.

When the library is included the application like this, everything works fine.

But since we are all good Angular developers, we know that the XML conversion might be used in mutiple places so lets create a nice factory for converting the data. So we create a factory like this and everything should work as expected.

But is doesnt, we get an nasty error that just doesnt seem to make any sense

TypeError: undefined is not a function

As it turns out when the factory is used and the function x2js.xml_str2json is called, it is not bound to the correct context so the function is failing. A little bit of a deeper dive into the x2js code revealed that I would need to bind the context of the object when making the call to get the correct results.

Use of the angular.bind function was the missing link, see code below.

I ended up writing a small test program to work through the issues and to use in a breakout session with the team at work. This sample is included in the CodePen below; the complete BikesNearMe project is accessible on Github. Link to that project is at the end of this post.


<< Click Here For All Articles on Ionic Framework >>


Here is the complete sample application running with CodePen

&lt;html ng-app=&quot;myApp&quot;&gt;
&lt;body ng-controller=&#x27;basicController&#x27;&gt;
&lt;h3&gt;Using xml2json in an angular factory&lt;/h3&gt;
&lt;p&gt;Attempting to convert the following xml string&lt;/p&gt;
&lt;div &gt;
&lt;p&gt;Without Using angular.bind&lt;/p&gt;
&lt;input text ng-model=&quot;xmlstring1&quot;/&gt;
&lt;button ng-click=&#x27;convertXML(true)&#x27;&gt;CONVERT XML&lt;/button&gt;
&lt;p&gt;Using angular bind&lt;/p&gt;
&lt;input text ng-model=&quot;xmlstring2&quot;/&gt;
&lt;button ng-click=&#x27;convertXML(false)&#x27;&gt;CONVERT XML&lt;/button&gt;

&lt;script src=&quot;;&gt;&lt;/script&gt;
&lt;script src=&quot;;&gt;&lt;/script&gt;

See the Pen <a href=’’>ifbLq</a> by aaron k saunders (<a href=’’>@aaronksaunders</a>) on <a href=’’>CodePen</a>.


Download BikesNearMe Ionic Framework Project from GitHub