简体   繁体   中英

React-Native fetch XML data

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

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.

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

var DOMParser = require('xmldom').DOMParser

I use it to my project.

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 

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

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

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.

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;

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 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM