React-Native 获取 XML 数据

IT技术 javascript xml json reactjs react-native
2021-05-13 14:45:53

我是 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>
    );
  },
});
4个回答

你可以试试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)
        })

我在我的项目中使用它。

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

var DOMParser = require('xmldom').DOMParser

我在我的项目中使用它。

首先 - React Native using JavaScriptCore,它只是一个javascript解释器,所以没有浏览器对象模型,没有文档对象,没有窗口等。这就是你不能使用的原因DOMParser,例如。

实际上 React 为您提供了一个XMLHttpRequest包装器,但它不包括responseXML.

我没有找到任何解决方案,所以我刚刚为此创建了自己的库:react-native-xml,它允许您解析 xml 并为其进行 XPath 查询:

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 

看起来您无法返回 XML,但可以获取原始文本;使用response.text()代替response.json(). 您仍然需要将文本处理为 xml