0

I am using angularjs and spring mvc in my application. angularjs invokes spring controller using rest. The controller invokes external URL that returns XML.

Now, I want to send this XML to angularjs in json format. I can convert the xml into java objects (using jaxb) and use jackson-databind jar to convert java into json. However, the xml structure returned from the external URL is dynamic and can change any time that is not under my control. In this scenario, if the xml structure changes, I will have to modify my java object. This is tedious.

Rather, if I can send the xml response directly to angularjs in the form of json, it will make my task easier.

Is there any way to achieve this?

Alternatively, can I invoke the external URL directly in angularjs? Will the returned xml be converted to json automatically? Or should I be using any component or JS library to convert it into json?

Maz
  • 653
  • 12
  • 22

1 Answers1

1

You can invoke the external URL directly and you must use 3rd party library for the xml conversion because angular don't provide the conversion itself with the manual http. I recommend x2js because it is simple and quite easy to understand for example on how to use it as below and if you want more details, please go through docs.

Controller

module.controller('exampleCtrl', function($scope,exampleSvc){

    function loadExternalXml(){
         var x2js = new X2JS();
         exampleSvc.getExternalXml().success(function(data){
              // part to convert xml to json
              var json = x2js.xml_str2json(data);
         });
   }
  });

Service

module.factory('exampleSvc',function($http){
   var factory = [];

   factory.getExternalXml = function(){
         return $http.get("http://cdn.rawgit.com/motyar/bcf1d2b36e8777fd77d6/raw/bfa8bc0d2d7990fdb910927815a40b572c0c1078/out.xml");
   }

    return factory;
 });
digit
  • 4,479
  • 3
  • 24
  • 43