Issue Parsing XML in react using ReactDOM

旧街凉风 提交于 2019-12-11 17:52:25

问题


i'm parsing an XML file in my React application from a file, if i write my file listener like hard coded xml i get a correct answer (2) :

const raw = `<?xml version="1.0" encoding="ISO-8859-1" ?>
  <?xml-stylesheet type="text/xsl" href="ACSPIXMT.xsl" ?>

  <IMPORT>
  <ACSPIX Type="2106" SN="UI00650521" Ver="3.05.01"/>
  <DEVICE  Name="Performa" SN="04666273"  ModelNum="591" Dt="2018-04-17" Tm="13:53" BGUnit="mg/dL">
  </DEVICE>
  <RECENTREC Dt="2014-02-11" Tm="18:47"/>
  <BGDATA>
  <BG Val="226" Dt="2014-02-11" Tm="18:47" D="1"/>
  <BG Val="149" Dt="2014-02-08" Tm="18:23" D="1"/>
  <BG Val="101" Dt="2014-02-07" Tm="20:56" D="1"/>
  <BG Val="275" Dt="2014-02-07" Tm="18:49" D="1"/>
  <BG Val="301" Dt="2014-02-06" Tm="19:13" D="1"/>
  <BG Val="112" Dt="2014-02-06" Tm="07:20" D="1"/>
  <BG Val="213" Dt="2014-02-05" Tm="19:42" D="1"/>
  <BG Val="111" Dt="2014-02-05" Tm="12:02" D="1"/>
  <BG Val="212" Dt="2014-02-04" Tm="19:18" D="1"/>
  </BGDATA>
  <STATISTIC>
  <ST_TIMERANGE Weeks="2" Dt="2014-02-11"/>
  <ST_EVALRESULTS Val="9"/>
  <ST_TSTFREQ1 Val="0.6"/>
  <ST_TSTFREQ2 Val="1.5"/>
  <ST_MBG Val="189"/>
  <ST_SD Val=" 74"/>
  <ST_HBGI Val="12.3"/>
  <ST_LBGI Val="0.0"/>
  </STATISTIC>
  <CHECK CRC="4816"/>
  </IMPORT>`;
const parser = new DOMParser();
const xml = parser.parseFromString(raw, 'text/xml');

console.log(xml.querySelector('ST_TIMERANGE').getAttribute('Weeks'));

but if i write my listener to read the actual file (which is exatly the same content) i dont get anything

handleSubmit(event) {

    const rawFile = new XMLHttpRequest();
    //here the file will be opened
    //submit pressed

    rawFile.onreadystatechange = () => {
      if (rawFile.readyState === 4 && (rawFile.status === 200 || rawFile.status === 0)) {




        const parser = new DOMParser();
        const xml = parser.parseFromString(rawFile.response, 'text/xml');

        var allText = rawFile.responseText;
        alert(allText);

        console.log(xml.querySelector('ST_TIMERANGE').getAttribute('Weeks'));

        // Do your querying here.
        // xml will can now be queried like DOM
        // var parsedResponse = xml.querySelector('ST_TIMERANGE').getAttribute('Weeks');
        // alert (xml.querySelector('ST_TIMERANGE')) // returns 2.

      }
    };

can you help me with it ? what am i doing wrong ?

here is my full file:

import React, { Component } from 'react';
import logo from './mainicon.png';
import './App.css';
import ReactDOM from 'react-dom';


class App extends Component {


// <img src={logo} className="App-logo" alt="logo" />



  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {

    const rawFile = new XMLHttpRequest();
    //here the file will be opened
    //submit pressed

    rawFile.onreadystatechange = () => {
      if (rawFile.readyState === 4 && (rawFile.status === 200 || rawFile.status === 0)) {




        const parser = new DOMParser();
        const xml = parser.parseFromString(rawFile.response, 'text/xml');

        var allText = rawFile.responseText;
        alert(allText);

        console.log(xml.querySelector('ST_TIMERANGE').getAttribute('Weeks'));

        // Do your querying here.
        // xml will can now be queried like DOM
        // var parsedResponse = xml.querySelector('ST_TIMERANGE').getAttribute('Weeks');
        // alert (xml.querySelector('ST_TIMERANGE')) // returns 2.

      }
    };

    rawFile.open('GET', this.App.files[0], false);
    rawFile.send();


    // var rawFile = new XMLHttpRequest();
    // var allText;
    // rawFile.open("GET", this.App.files[0], false);
    // rawFile.onreadystatechange = function ()
    // {
    //     if(rawFile.readyState === 4)
    //     {
    //         if(rawFile.status === 200 || rawFile.status == 0)
    //         {
    //             allText = rawFile.responseText;
    //             // alert(allText);
    //         }
    //     }
    // }
    // rawFile.send(null);
    //
    // alert(allText);

  }


  render() {
    return (
      <div className="App">
        <header className="App-header">

          <img src={logo} />
          <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>


      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

export default App;

回答1:


So what you're trying to do is allowing the client user to choose a file and then your app will attempt to parse the XML file and grab a value. You do not need to use "XMLHttpRequest", but instead you can use the native browser "FileReader" which will asynchronously read the chosen file and through a callback, you receive the contents of the file.

One main thing you needed to add was "event.preventDefault()" in order to have the page not refresh after you press "submit". The second main thing was to replace your "XMLHttpRequest", with "FileReader".

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {

    constructor(props) {
      super(props);
      this.handleSubmit = this.handleSubmit.bind(this);
      this.state = {output: ''};
    }

    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');

        alert(xml);

        const output = xml.querySelector('ST_TIMERANGE').getAttribute('Weeks');

        this.setState({output})
      };  
    }

    render() {
      return (
        <div className="App">
          <header className="App-header">

            <img src={logo} />
            <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: {this.state.output}</h2>

        </div>
      );
    }
  }



ReactDOM.render(
  <App />,
  document.getElementById('root')
);

export default App;


来源:https://stackoverflow.com/questions/50443855/issue-parsing-xml-in-react-using-reactdom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!