Read the XML file in the React application

Tram Ho

In recent times, our team has built a project to read and extract electronic invoice data from XML files. Read online, there is no specific tutorial on reading files from the client-side, mostly from server-side like NodeJS. So today I’m going to write a specific tutorial on how you can read XML files from React and turn data into a key-value pair in JSON.

Read the XML file from local after the user uploads it

Suppose the user needs to upload the file directly from their computer to the browser. We will build a simple form with “file” input and allow users to upload files “application / xml” or “text / xml”:

To update the changes and save the file to the state after the user has selected the file, I will use the changeHandler function as follows:

However, if you notice when we console.log(e.target.files[0]) will return a File-type object with the “name” attribute. We absolutely cannot read its contents. To read the contents of the file, we can use the Web APIs FileReader :

After reading the file, I save the readings to a new variable called “readerData”. However, even if you console.log(readerData) , the results will look like this:

The reason for this is that the File object can be “serialized” – in other words, for the file to be transmitted via HTTP, the file must be able to be encoded as a string value.

If you have used JSON.stringify () and JSON.parse (), the principle of operation is the same as in this case. We need to “deserialize” the XML file stored in the state. One library that can help us with this is xml2js

To install xml2js:

Then, you import xml2js and use the following:

So after you console.log(content) , we will get the result returned as an object with the content of the XML file. You can track the entire sourcecode here:

Edit friendly-mirzakhani-7i38h

Share the news now

Source : Viblo