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() Commented 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? Commented Jan 21, 2016 at 3:10

9 Answers 9

19

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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";
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.
5

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

var DOMParser = require('xmldom').DOMParser

I use it to my project.

4 Comments

Has anyone tried to use xmldom specifically in React Native?
I use it in my demo project. you can refer to the demo github.com/kaich/ASReact/blob/master/App/Main/TypePage.js
Does it support both Android and iOS?
@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.
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 Comment

Very pretty solution but it does not seem to support Android. So you would still have the same problem there.
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 Comments

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 :(
Also i've got "Can't find variable: DOMParser()" when using new DOMParser();
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

Comments

0

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 Comments

How come this is upvoted? It answers a totally different question; how to send an URL as a get parameter.
I think it's using a Google service to convert an XML file into JSON…
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.

Comments

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

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.