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>
    );
  },
});
Toon
  • 652
  • 1
  • 11
  • 24

9 Answers9

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.

lam luu
  • 792
  • 9
  • 7
  • 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 '19 at 03: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 02 '19 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.

Robert
  • 5,278
  • 43
  • 65
  • 115
kai
  • 310
  • 3
  • 14
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

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

Aaron Saunders
  • 33,180
  • 5
  • 60
  • 80
  • Yes, response.text() works fine, but there is a problem with text to xml process. For example all solutions from [these](http://stackoverflow.com/questions/17604071/parse-xml-using-javascript) answers return null or error :( – Toon Apr 25 '15 at 09:51
  • Also i've got "Can't find variable: DOMParser()" when using new DOMParser(); – Toon Apr 25 '15 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

Matansh
  • 764
  • 4
  • 13
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.

Sahil Khurana
  • 478
  • 4
  • 10
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;
Ali Shirazee
  • 1,008
  • 10
  • 11
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)
    })
David Buck
  • 3,752
  • 35
  • 31
  • 35
-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!

Ramon Gebben
  • 534
  • 4
  • 17