简体   繁体   English

如何从 React JS 的 react 项目的公共目录中的文件中读取 xml?

[英]How to read xml from file inside public directory in react project in React JS?

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在我的反应项目公共文件夹中,我有一个名为mySurvey.xml的文件,我想在我的 src 目录中读取该文件,因此为简单起见,我尝试在 app.js 中读取它

在此处输入图像描述

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.因此,在我的 app.js 中,我尝试使用fetch API读取它,但它返回 index.html 文本作为响应,而不是文件的内容。

 // 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);

在此处输入图像描述 }) })

In the network tab, I checked fetch API is creating this url http://localhost:3000/mySurvey.xml 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这会加载 html 页面并且不会放弃 xml 数据

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.注意:- 公用文件夹中有很多 xml 文件,例如 mySurvey.xml,我将收到基于文件名的文件名,我必须从中读取数据。

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. Fetch 默认无法解析 xml。 So, I am using DOMParser to parse the string to an XML object.因此,我使用 DOMParser 将字符串解析为 XML object。 As soon as you get the xml object, you can store it in your state and manipulate it as you wish一旦您获得 xml object,您就可以将其存储在您的 state 中并根据需要进行操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM