2

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 Answer 1

3
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

Sign up to request clarification or add additional context in comments.

6 Comments

Basically, my problem is I am unable to reach to mySurvey.xml in fetch request
@John That is weird. It should fetch from public folder without any problem. I just tried it out a new project on my machine and it worked
In which file did you write the fetch API code, can you share the screen shot please of that file and code
@John He wrote in App.js in src as far as I got to know
In the network tab, I checked fetch API is creating this url localhost:3000/mySurvey.xml And this loads up the html page And doesn't give up xml data
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.