'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



Solution 1:[1]

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});
},

Solution 2:[2]

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

Solution 3:[3]

hope so this will helpful

first Install the dependency

npm i xml-js

xml Documentation

Run this code Snippet it will convert your Xml file to Json or Js file and destruct the data.

expo Online Editor

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import convert from 'xml-js'; ///if this library will create issue then 
var parseString = require('react-native-xml2js').parseString;

var xml =`<?xml version="1.0" encoding="utf-8"?>
  <appSettings>
    <!-- CONFIGURACOES IIS -->
    <add key="ProjetoCliente" value="ESocialDev2019" />
    <add key="URLProjeto" value="http://localhost/ESocialDev2019" />
    <add key="URLLogin" value="http://localhost/ESocialDev2019/F3M" />
    <!-- /CONFIGURACOES IIS -->
    <!-- CONFIGURACOES BASEDADOS -->
    <add key="ModoSAAS" value="False" />
    <add key="NomeBDSAAS" value="F3MESocial" />
    <add key="ServidorSQL" value="DSI-SQL-01" />
    <add key="InstanciaSQL" value="F3M2014" />
    <add key="UtilizadorSQL" value="F3MES" />
    <add key="PasswordSQL" value="" />
    <add key="PasswordSQLSA" value="" />
    <add key="BDEmpresa" value="F3MES" />
    <add key="BDGeral" value="F3MESGeral" />
    <!-- /CONFIGURACOES BASEDADOS -->
  </appSettings>`;

export default function App() {
  React.useEffect(()=>{


// Solution One
const json = xmltoJson(xml)
console.log("test", json)



  // Solution Two 

    parseString(xml, function (err, result) {
    console.log(JSON.parse(result));
});
  },[])
  const xmltoJson=(xml)=>{
    return convert.xml2js(xml)
  }
  return (
    <View style={styles.container}/>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Reza
Solution 2
Solution 3