Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use XML response in react-native

I am developing an mobile application by react-native, I have to call a odata service which returns XML and I need to convert that to json object.

How should I do that?

return fetch(url, {
      method: 'GET',
      headers: {
        Authorization: config.api.auth,
      },
    })
      .then(response => response.json())
      // .then(response => response.text())
      // .then(xml => _xmlToJson(xml))
      .then(json => dosomething(json))
      .catch(ex => showError(ex));
  };

I tried to get text() instead on json() and pass it to another method which converts xml to json but the problem is that method needs a xml object but text() returns string, and I couldn't find a way in react-native to convert string to xml.

p.s. Since React Native using JavaScriptCore, which is just a javascript interpreter, so no Browser Object Model, no document object, no window, etc can be used

like image 777
Reza Avatar asked May 16 '16 17:05

Reza


2 Answers

Although answer of Daniel Schmidt is correct, I used the way that is described in this article, Build a YouTube playlist browser with React Native and Siphon

npm install xmldom 

var DOMParser = require('xmldom').DOMParser;

parseVideos: function(s) {
  console.log('Parsing the feed...');
  var doc = new DOMParser().parseFromString(s, 'text/xml');
  var objs = [];
  var videos = doc.getElementsByTagName('yt:videoId');
  var thumbs = doc.getElementsByTagName('media:thumbnail');
  for (var i=0; i < videos.length; i++) {
    objs.push({
      id: videos[i].textContent,
      thumbnail: thumbs[i].getAttribute('url')
    })
  }
  this.setState({videos: objs});
},
like image 183
Reza Avatar answered Oct 25 '22 02:10

Reza


You may use any xml2js library there is in the node realm, for example https://github.com/Leonidas-from-XIV/node-xml2js

like image 38
Daniel Schmidt Avatar answered Oct 25 '22 02:10

Daniel Schmidt