29

I'm new to React-Native. Trying to make some very simple apps. Can't figure out how to fetch XML data. With JSON everything is clear and simple.

But how to fetch XML? Tried to convert it to JSON via this and some other similar scripts, but without any success. Need help :/

My code looks very simple:

var xml_url = 'http://api.example.com/public/all.xml';

var ExampleProject = React.createClass({
    getInitialState: function() {
    return {
      data: {results:{}},
    };
  },
  componentDidMount: function() {
    this.fetchData();
  },
  fetchData: function() {
    fetch(xml_url)
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          data: responseData.data,
        });
      })
      .done();
  },

  render: function() {
    return (
      <View style={styles.wrapper}>
        <View style={styles.container}>
          <View style={styles.box}>
            <Text style={styles.heading}>Heading</Text>
            <Text>Some text</Text>
          </View>
        </View>
      </View>
    );
  },
});
2
  • 1
    Try using response.text()
    – potench
    Jul 28, 2015 at 3:46
  • Any answer on this? I've run into the same problem. Is there no pure JS XML parser out there?
    – nicholas
    Jan 21, 2016 at 3:10

9 Answers 9

18

you can try https://github.com/connected-lab/react-native-xml2js ,

    const parseString = require('react-native-xml2js').parseString;

    fetch('link')
        .then(response => response.text())
        .then((response) => {
            parseString(response, function (err, result) {
                console.log(response)
            });
        }).catch((err) => {
            console.log('fetch', err)
        })

I use it to my project.

2
  • As of Feb, 2019 this answer still appears to be the most relevant. You may want to switch to ES6 import syntax instead though to keep up with current conventions: import { parseString } from "react-native-xml2js";
    – huwiler
    Feb 15, 2019 at 3:50
  • newb question, after npm install react-native-xml2js, I get "Module not found: Can't resolve 'react-native-xml2js' in '/Users/me/firsttry/src/components'" when I use that import.
    – Mark
    Apr 2, 2019 at 13:54
5

you can use npm install xmldom, now load DOMParser as below :

var DOMParser = require('xmldom').DOMParser

I use it to my project.

4
  • Has anyone tried to use xmldom specifically in React Native? Jan 11, 2016 at 6:12
  • 1
    I use it in my demo project. you can refer to the demo github.com/kaich/ASReact/blob/master/App/Main/TypePage.js
    – kai
    Jan 11, 2016 at 10:05
  • Does it support both Android and iOS? Jan 12, 2016 at 3:59
  • @LawGimenez Today I just used xmldom to process an RSS feed. I'm still in the early stages but it seems to work fine with iOS and Android.
    – Brendan
    Aug 3, 2016 at 21:26
2

First of all - React Native using JavaScriptCore, which is just a javascript interpreter, so no Browser Object Model, no document object, no window, etc. That's a reason why you cannot use DOMParser for example.

Indeed React provides you a XMLHttpRequest wrapper, but it doesn't include responseXML.

I didn't found any solution for this, so I've just created my own library for that: react-native-xml which allows you to parse xml and make XPath queries for it:

let xml = require('NativeModules').RNMXml
xml.find('<doc a="V1">V2</doc>', 
         ['/doc/@a', '/doc'], 
          results => results.map(nodes => console.log(nodes[0]))) 
// Output: 
//  V1 
//  V2 
1
  • 1
    Very pretty solution but it does not seem to support Android. So you would still have the same problem there. Jan 26, 2016 at 5:56
1

looks like you cannot get XML back but you can get the raw text; use response.text() instead of response.json(). you will still need to process the text into xml

2
  • Yes, response.text() works fine, but there is a problem with text to xml process. For example all solutions from these answers return null or error :(
    – Toon
    Apr 25, 2015 at 9:51
  • Also i've got "Can't find variable: DOMParser()" when using new DOMParser();
    – Toon
    Apr 25, 2015 at 10:21
1

I am using react-native, and I didn't really like xmldom. I wrote my own react-native XML parser. You can check it on https://www.npmjs.com/package/react-xml-parser

0

I used a combination of 2 packages. In my use case I had to parse response of a SOAP request:

The first package is - React Native XML2JS The reason for using it and not XML2JS is I was getting an error of React Native not supporting node standard library. (I am using expo as well.)

The second package which I actually used for parsing is - XML-JS. I had to use the first package as I was getting the same error of React Native not supporting node standard library. I used this because it gave a more structured result in case of a large XML response.

0
const parseString = require('react-native-xml2js').parseString;

fetch('link')
    .then(response => response.text())
    .then((response) => {
        parseString(response, function (err, result) {
            console.log(response)
        });
    }).catch((err) => {
        console.log('fetch', err)
    })
0

Here is a working example with xml2js :

• responseText is is the .XML data fetched from example.xml

• within the curly braces of .then((responseText) = {}) the xml2json script is added to parse the .xml data to Json format console.log(result) will render the json format in the terminal.

side note : if you remove the parse string and add console.log(responseText) instead the output will be XML format.

    import React, {Component} from 'react';
    import {View} from 'react-native';
    import {parseString} from 'xml2js'



    class App extends Component {


     componentDidMount(){
      this._isMounted = true;
      var url = "https://example.xml"
      fetch(url)
        .then((response) => response.text())
        .then((responseText) => {
       parseString(responseText, function (err, result) {
         console.log(result);
         return result;
        });
      this.setState({
        datasource : result
        })
       })
    .catch((error) => {
      console.log('Error fetching the feed: ', error);
    });
  }



      componentWillUnMount() {
         this._isMounted = false;
      }




      render(){
        return(
          <View>

          </View>

        )
      }
    }

    export default App;

-1

I had the same problem spend a few hours before I found out that I could do it like this:

const GOOGLE_FEED_API_URL = "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=-1&q="
let url = GOOGLE_FEED_API_URL + encodeURIComponent(<yoururl>);

fetch(url).then((res) => res.json());

Hope it helps!

2
  • 2
    How come this is upvoted? It answers a totally different question; how to send an URL as a get parameter. Nov 4, 2015 at 13:53
  • I think it's using a Google service to convert an XML file into JSON… Jun 7, 2016 at 20:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.