Converting xml file data in js object

462 views Asked by At

I need some help. I have an app that takes *.xml file through input type file, and converts it into js object. To do that i am using FileReader and xml-js library from here https://www.npmjs.com/package/xml-js

Now I have two problems that I can't handle.

  1. xml file contains cyrillic symbols, in console they display as ������� ��� ��� enter image description here
  1. The second problem is that, in some reasons, I can't set converted object in state.

Here is my code: Handler and input for file:

handleFile = (event) => {
    let file = event.target.files[0];
    let reader = new FileReader();
    reader.readAsText(file);
    reader.onloadend = () => {
        let json = xmljs.xml2js(reader.result, {compact: true, spaces: 4});
        this.setState({
            file: json
        }, console.log ('file', json))
    }
};

render() {

    return (
        <div>
            <input type="file" onChange={this.handleFile}/>
        </div>
    )
}

So what shouls I do to display cyrillic symbols and how to set the object in state?

1

There are 1 answers

0
Stas Motorny On BEST ANSWER

I fixed it. Now my code looks so:

handleFile = (event) => {
    let file = event.target.files[0];
    let reader = new FileReader();
    reader.readAsText(file, 'windows-1251');
    reader.onloadend = () => {
        let json = xmljs.xml2js(reader.result, {compact: true, spaces: 4});
        this.setState({
            file: json
        }, () => {console.log('state', this.state)})
    }
};

render() {

    return (
        <div>
            <input type="file" onChange={this.handleFile}/>
        </div>
    )
}

I added 'windows-1251' to define the encoding type, it helps with cyrillic symbols. Also i changed callback function after setState to () => {console.log('state', this.state)} after that I can see a current state, with contetnt fron xml file.