2
votes

Inside my react project public folder, I have a file named mySurvey.xml, I want to read that file inside my src directory, so for simplicity i tried reading it inside app.js

enter image description here

So inside my app.js I tried reading it with fetch API, but it returns the index.html text as response and not the content of the file.

 // Fetch Function   
   fetch("./mySurvey.xml")
   .then(response => response.text())
   .then(data=>{
     console.log('File Data = ',data)
     let parser = new DOMParser();
     let xml = parser.parseFromString(data, "application/xml"); 
     console.log('XML = ',xml);
   })
  .catch(error =>{
     console.log('My Error = ',error);

enter image description here })

In the network tab, I checked fetch API is creating this url http://localhost:3000/mySurvey.xml

And this loads up the html page And doesn't give up xml data

Please guide me is my approach correct or is there a better way!!

Note:- There are a lot of xml files inside public folder like mySurvey.xml and I will receive fileName based on which I have to read data from.

1

1 Answers

2
votes
fetch('abc.xml')
      .then((res) => res.text())
      .then(xmlString => new window.DOMParser().parseFromString(xmlString, "text/xml"))
      .then(data => setItem(data))
      .catch((err) => {
        console.log(err);
      });

Fetch cannot parse xml by default. So, I am using DOMParser to parse the string to an XML object. As soon as you get the xml object, you can store it in your state and manipulate it as you wish