Javascript React-Native 获取 XML 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29805704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:02:14  来源:igfitidea点击:

React-Native fetch XML data

javascriptxmljsonreactjsreact-native

提问by Toon

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.

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

But how to fetch XML? Tried to convert it to JSON via thisand some other similar scripts, but without any success. Need help :/

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

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

采纳答案by lam luu

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.

我在我的项目中使用它。

回答by kai

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.

我在我的项目中使用它。

回答by Artem Yarulin

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 DOMParserfor example.

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

Indeed React provides you a XMLHttpRequestwrapper, 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-xmlwhich 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 

回答by Aaron Saunders

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

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

回答by Matansh

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

我正在使用 react-native,但我并不喜欢 xmldom。我编写了自己的 react-native XML 解析器。您可以在https://www.npmjs.com/package/react-xml-parser上查看

回答by Sahil Khurana

I used a combination of 2 packages. In my use case I had to parse response of a SOAP request:

我使用了 2 个包的组合。在我的用例中,我必须解析 SOAP 请求的响应:

The first package is - React Native XML2JSThe reason for using it and not XML2JSis I was getting an error of React Native not supporting node standard library. (I am using expo as well.)

第一包是-阵营本地XML2JS之所以使用它,而不是XML2JS是我得到的错误做出反应原住民不支持节点标准库。(我也在使用世博会。)

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.

我实际用于解析的第二个包是 - XML-JS。我不得不使用第一个包,因为我遇到了 React Native 不支持节点标准库的相同错误。我使用它是因为它在大型 XML 响应的情况下提供了更结构化的结果。

回答by Ali Shirazee

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, hope this helps.

旁注:如果您删除解析字符串并添加 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;

回答by Ramon Gebben

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!

希望能帮助到你!