Issue Parsing Xml In React Using Reactdom
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 = `
Solution 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".
importReact, { Component } from'react';
import logo from'./logo.svg';
import'./App.css';
classAppextendsComponent {
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 = newFileReader();
reader.readAsText(file);
reader.onloadend = (evt) => {
const readerData = evt.target.result;
const parser = newDOMParser();
const xml = parser.parseFromString(readerData, 'text/xml');
alert(xml);
const output = xml.querySelector('ST_TIMERANGE').getAttribute('Weeks');
this.setState({output})
};
}
render() {
return (
<divclassName="App"><headerclassName="App-header"><imgsrc={logo} /><h1className="App-title">Insulog</h1></header><pclassName="App-intro">
Please Enter your insulog XML file at the button below
</p><formonSubmit={this.handleSubmit}><label>
Upload file:
<inputtype="file"ref={input => {
this.App = input;
}}
/>
</label><br /><buttontype="submit">Submit</button></form><h2>XML Readings of ST_TIMERANGE and WEEKS: {this.state.output}</h2></div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
exportdefaultApp;
Post a Comment for "Issue Parsing Xml In React Using Reactdom"