How convert XML input file to json


#1

In my app, i want to get the xml file as input with http request and convert it to json. vice versa as well. X2jS helped me in achieving this in ionic 1. But i am not getting it worked in ionic 2. How to achieve this in ionic2. Please help.


#2

I got it working with RXJS. Thanks :slight_smile:


#3

why do you not working directly with json in a modern web-app :wink:


#4

My server data are in XML format and i want to convert to json. :smile:


#5

yeah but why are you using xml on your backend ? If you have the chance to choose or hange to json --> do it ^^


#6

Sure @bengtler. Those are plan for future. Currently checking with the existing data.


#7

Hi @AishApp could you provide a code sample using RXJS please?
it could help me, I need to do the same process :grinning:


#8

Hi @ekoz,
Some changes has been made in Angular 2 now due to which there should be change in code too.
Install xml2json from npm and xml2json.d.ts from typings.
In your service use the below code

import * as x2js  from 'xml2json';
myjson(){
var req = this.http.get("my_link_for_xml");
return req.map((res:Response) => {
let c = res.text();
let myJson = x2js.xml_str2json(c);
return myJson;
});
}

#9

thanks you for your reply! sorry to ask you again, but how did you install xml2json, I got the node-gyp rebuild error on npm install, did you get it?I tried one hundred fix… nothing helped :frowning:


#10

Have you installed the typings?


#11

yes I have installed the typings,
but the npm install xml2json has some error on my windows…
if it wasn’t the case for you I will try another method again :wink:


#12

I tried using xml2json very long before. May be you can have a try on xml2js library.


Convert xml to json in Ionic2 framework (Typescript)
#13

Thanks a lot, it works! how to do if it can help somenone :

  1. myApp> npm install xml2js --save

  2. myApp> typings install dt~xml2js --global --save

  3. in your component, service, etc… : import * as xml2js from "xml2js";

  4. code sample :

    xml2js.parseString(myXmlString, function (err, result) {
    console.log(result);
    });


Webservice result like dictionary
#14

Thanks for your advice. I tried it but it still doesn`t work for me. The console tells me that the return value is undefined. The http return is type of object.

Here my code:

makeGetRequest() {
    this.http.get('http://www.gazetaexpress.com/rss/sport/?xml=1').subscribe(data => {
        this.posts = JSON.stringify(data);
        console.log(typeof(this.posts));
        xml2js.parseString(this.posts, function (err, result) {
            console.log(result);
        });
    }, error => {
        console.log(JSON.stringify(error.json()));
    });
}

The same result even if I dont strigify the subscribed data. Hope you can help me cause I am going nuts


#15

Hi @Goni1605, you have to do your operations under observable map. Try to modify your code as below.

makeGetRequest() {
this.http.get(‘http://www.gazetaexpress.com/rss/sport/?xml=1’).map(res => {
let posts = res.json();
xml2js.parseString(posts, ((result) => {
console.log(result);
return result;
}));
}).subscribe(
(data) => console.log(data),
(err) => console.log(err)
);


#16

Does anyone import xml2js into ionic RC0 ?
When I try I got this error :
https://forum.ionicframework.com/t/rc0-how-to-import-xml2js/65146


#17

I’m having issues with my GET request. I add xml2js but i keep getting XMLHttpRequest cannot load. But i see the console in Chrome (the Network tab) i can see that the server return status code 200.
Any help?


#18

Since things have changed over time with JSON now begin the default response type for every request (as of Angular 4.3.0), the possibilities the HttpInterceptor creates (ditto Angular 4.3.0) and with the introduction of lettable operators (RxJS 5.5.2), it seems reasonable to add an answer. On the blogpost (source: https://www.ionicrun.com/transform-xml-to-json-in-ionic-2-with-angular-4-3/) an HttpInterceptor is used as well to make things even more generic (but that is to much to post here).

Install your packages / types (or whatever XML - JSON lib you prefer).

npm i xml2js --save
npm i @types/xml2js --save-dev

Create a TransformProvider, responsible for transforming your XML to JSON

// transform.ts

import { Injectable } from '@angular/core';
import xml2js from 'xml2js';

@Injectable()
export class TransformProvider {

  public convertToJson(data: string): Object {

    let res;

    // setting the explicitArray option prevents an array structure
    xml2js.parseString(data, { explicitArray: false }, (error, result) => {
      
      if (error) {
        throw new Error(error);
      } else {
        res = result;
      }

    });

    return res;

  }

}

A DataProvider or whatever place you want to make your HTTP / call.

// lettable import
import { map } from 'rxjs/operators/map';
...

public getRandomUser() {
  return this
    .http
    .get('https://randomuser.me/api/?format=xml', { responseType: "text" })      
    // use the pipe method
    .pipe(
      // ... to apply oprtators to obervables
      map((res: string) => this.transformProvider.convertToJson(res))
    )
    .subscribe((res: Object) => {
      // do whatever you wanna do with your data
      console.dir(res);
    });
}

#19

var self = this;
this.http.get(’/assets/xml/app.xml’).subscribe(data => {

    xml2js.parseString(data.text(), function (err, result) {
        console.log('result',result);
        self.posts = JSON.stringify(result);
       console.log('type of',self.posts);
    });
}, error => {
    console.log(JSON.stringify(error.json()));
});

#20

Dont use var but let
Dont use function but fat arrow ()=>{}
Then you dont need to do self=this

And have the full context available