简体   繁体   English

React-Native 获取 XML 数据

[英]React-Native fetch XML data

I'm new to React-Native.我是 React-Native 的新手。 Trying to make some very simple apps.尝试制作一些非常简单的应用程序。 Can't figure out how to fetch XML data.无法弄清楚如何获取 XML 数据。 With JSON everything is clear and simple.使用 JSON,一切都变得清晰而简单。

But how to fetch XML?但是如何获取 XML? Tried to convert it to JSON via this and some other similar scripts, but without any success.试图通过这个和其他一些类似的脚本将它转换为 JSON,但没有任何成功。 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 ,你可以试试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 :你可以使用npm install xmldom ,现在加载 DOMParser 如下:

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.首先 - React Native 使用JavaScriptCore ,它只是一个 javascript 解释器,所以没有浏览器对象模型,没有文档对象,没有窗口等。这就是你不能使用DOMParser的原因。

Indeed React provides you a XMLHttpRequest wrapper, but it doesn't include responseXML .实际上 React 为您提供了一个XMLHttpRequest包装器,但它不包括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:我没有找到任何解决方案,所以我刚刚为此创建了自己的库: 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 

looks like you cannot get XML back but you can get the raw text;看起来您无法取回 XML,但您可以获得原始文本; use response.text() instead of response.json() .使用response.text()而不是response.json() you will still need to process the text into xml您仍然需要将文本处理为 xml

I am using react-native, and I didn't really like xmldom.我正在使用 react-native,但我并不喜欢 xmldom。 I wrote my own react-native XML parser.我编写了自己的 react-native XML 解析器。 You can check it on https://www.npmjs.com/package/react-xml-parser您可以在https://www.npmjs.com/package/react-xml-parser上查看

I used a combination of 2 packages.我使用了 2 个包的组合。 In my use case I had to parse response of a SOAP request:在我的用例中,我必须解析 SOAP 请求的响应:

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 .第一包是-阵营本地XML2JS之所以使用它,而不是XML2JS是我得到的错误做出反应原住民不支持节点标准库 (I am using expo as well.) (我也在使用世博会。)

The second package which I actually used for parsing is - XML-JS .我实际用于解析的第二个包是 - XML-JS I had to use the first package as I was getting the same error of React Native not supporting node standard library.我不得不使用第一个包,因为我遇到了 React Native 不支持节点标准库的相同错误。 I used this because it gave a more structured result in case of a large XML response.我使用它是因为它在大型 XML 响应的情况下提供了更结构化的结果。

Here is a working example with xml2js :这是一个使用 xml2js 的工作示例:

• responseText is is the .XML data fetched from example.xml • responseText 是从 example.xml 获取的 .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. • 在.then((responseText) = {}) 的大括号内,添加了xml2json 脚本以将.xml 数据解析为Json 格式console.log(result) 将在终端中呈现json 格式。

side note : if you remove the parse string and add console.log(responseText) instead the output will be XML format.旁注:如果删除解析字符串并添加 console.log(responseText) ,则输出将为 XML 格式。

 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!希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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