如何在React JS中读取XML文件(data.xml)?

时间:2019-11-05 04:58:57

标签: reactjs xml-parsing

我尝试读取xml文件并使用react-xml-parser库进行解析。

 var XMLParser = require('react-xml-parser');
 var xml = new XMLParser().parseFromString(xml_string);
 console.log(xml);
 console.log(xml.getElementsByTagName('Row'));

在这里,它应该从字符串中读取,但是我需要从文件中获取它。 我的xml文件位于目录xmldata/list.xml中,所以我现在不怎么做。


尝试了此代码:

import XMLData from '../../xmldata/list.xml';
function ReadData() {
          var jsonDataFromXml = new XMLParser().parseFromString(XMLData);
          console.log(jsonDataFromXml);
          console.log(jsonDataFromXml.getElementsByTagName('Row'));

        }
    }
}

结构文件夹

-src
   |—views
        |—AdminScreen
               |—AdminScreen.js <-here used list.xml
   |—xmldata
           |—list.xml 

但结果是:

bundle.js:81 Uncaught TypeError: Cannot set property 'value' of undefined
    at bundle.js:81
    at Array.map (<anonymous>)
    at e.value (bundle.js:76)
    at e.value (bundle.js:148)
    at ReadData (AdminScreen.js:36)
    at AdminScreen (AdminScreen.js:14)
    at renderWithHooks (react-dom.development.js:15821)
    at mountIndeterminateComponent (react-dom.development.js:18141)
    at beginWork$1 (react-dom.development.js:19357)
    at HTMLUnknownElement.callCallback (react-dom.development.js:363)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:412)
    at invokeGuardedCallback (react-dom.development.js:466)
    at beginWork$$1 (react-dom.development.js:24570)
    at performUnitOfWork (react-dom.development.js:23505)
    at workLoopSync (react-dom.development.js:23480)
    at renderRoot (react-dom.development.js:23155)
    at scheduleUpdateOnFiber (react-dom.development.js:22653)
    at scheduleRootUpdate (react-dom.development.js:25686)
    at updateContainerAtExpirationTime (react-dom.development.js:25712)
    at updateContainer (react-dom.development.js:25812)
    at react-dom.development.js:26370
    at unbatchedUpdates (react-dom.development.js:22952)
    at legacyRenderSubtreeIntoContainer (react-dom.development.js:26369)
    at Object.render (react-dom.development.js:26460)
    at Module../src/index.js (index.js:30)
    at __webpack_require__ (bootstrap:785)
    at fn (bootstrap:150)
    at Object.0 (index.js:2)
    at __webpack_require__ (bootstrap:785)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
    at main.chunk.js:1

4 个答案:

答案 0 :(得分:3)

要读取本地文件,您有两个选择,可以使用XMLHttpRequest或axios。 使用XMlHttpRequest:

import XMLData from '../../xmldata/list.xml';

var rawFile = new XMLHttpRequest();
rawFile.open("GET", XMLData, false);
rawFile.onreadystatechange = () => {
    if (rawFile.readyState === 4) {
        if (rawFile.status === 200 || rawFile.status == 0) {
            var xmlasstring = rawFile.responseText;
            console.log('Your xml file as string', xmlasstring)
        }
    }

我建议使用axios bcz,它在使用Reactjs时是更方便,更好的选择 使用axios:

import XMLData from '../../xmldata/list.xml';

axios.get(XMLData, {
   "Content-Type": "application/xml; charset=utf-8"
})
.then((response) => {
   console.log('Your xml file as string', response.data);
});

现在,获取xml之后,您可以根据需要使用npm包(例如react-xml-parser,xml2js)来创建对象或json。我建议使用xml2js很好。而且我相信现在您也可以发送“ POST”请求以更新您的xml。

答案 1 :(得分:1)

  

如果您的数据来自后端,那么您可以直接使用该数据   作为xml_data。但是在您的情况下,您尝试从.XML导入数据   文件,但我没有找到直接访问XML文件的任何方法   反应。

解决方案:

您需要创建如下所示的 xml_data.js 文件,以导入XML数据

const xml_data = `<?xml version='1.0' encoding='utf-8'?>
<?xml-stylesheet type="text/xsl" href="ACSPIXMT.xsl" ?>

<Library>
   <Books count='1'>
       <Book id='1'>
           <Name>Me Before You</Name>
           <Author>Jojo Moyes</Author>
       </Book>
   </Books>
   <Music count=1>
       <CD id='2'>
           <Name>Houses of the Holy</Name>
           <Artist>Led Zeppelin</Artist>
       </CD>
   </Music>
</Library>`
    
export default xml_data;

Import xml_data from 'path of your xml file';
var xml = new XMLParser().parseFromString(xml_data);

希望这会对您有所帮助。让我知道您是否有任何问题。

答案 2 :(得分:1)

尝试以下代码。

at kz.sud.cabinet.web.login.AuthenticationManager.redirectToDefaultPage(AuthenticationManager.java:409)

list.xml

import xmlData from '../../xmldata/list.xml';
import XMLParser from 'react-xml-parser';

var jsonDataFromXml = new XMLParser().parseFromString(xmlData);

您的数据将在'jsonDataFromXml'变量中。

注意:

如果您的数据位于src目录中,请使用适当的路径并取消注释“ Suggestion 2”,否则,如果文件夹与src文件夹平行,则取消注释“ Suggestion 1”。

最好还是检查数据有效性,以防它始终不是XML文件。

答案 3 :(得分:0)

您无需将xml转换为js

这是对我有用的解决方案

import React, { Component } from "react";
import XMLParser from "react-xml-parser";
import List from "../xml.xml";

class App extends Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = {};
  }

  handleSubmit(event) {
    event.preventDefault();

    const file = this.App.files[0];

    const reader = new FileReader();

    reader.readAsText(file);

    reader.onloadend = evt => {
      const readerData = evt.target.result;

      const parser = new DOMParser();
      const xml = parser.parseFromString(readerData, "text/xml");

      console.log(
        "data",
        new XMLSerializer().serializeToString(xml.documentElement)
      );
      var XMLParser = require("react-xml-parser");
      var NewXml = new XMLParser().parseFromString(
        new XMLSerializer().serializeToString(xml.documentElement)
      ); // Assume xmlText contains the example XML
      console.log("newxml", NewXml);

      this.setState({ xml });
    };
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Insulog</h1>
        </header>
        <p className="App-intro">
          Please Enter your insulog XML file at the button below
        </p>

        <form onSubmit={this.handleSubmit}>
          <label>
            Upload file:
            <input
              type="file"
              ref={input => {
                this.App = input;
              }}
            />
          </label>
          <br />
          <button type="submit">Submit</button>
        </form>

        <h2>XML Readings of ST_TIMERANGE and WEEKS: </h2>
      </div>
    );
  }
}
export default App;