React-Native获取XML数据

Too*_*oon 22 javascript xml json reactjs react-native

我是React-Native的新手.试着制作一些非常简单的应用程序.无法弄清楚如何获取XML数据.使用JSON,一切都清晰简单.

但是如何获取XML?试图通过这个和其他类似的脚本将其转换为JSON ,但没有任何成功.需要帮忙 :/

我的代码看起来很简单:

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>
    );
  },
});
Run Code Online (Sandbox Code Playgroud)

小智 12

你可以试试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)
        })
Run Code Online (Sandbox Code Playgroud)

我用它来做我的项目.


小智 5

你可以使用npm install xmldom,现在加载DOMParser如下:

var DOMParser = require('xmldom').DOMParser
Run Code Online (Sandbox Code Playgroud)

我用它来做我的项目.