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
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});
},
You may use any xml2js library there is in the node realm, for example https://github.com/Leonidas-from-XIV/node-xml2js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With