簡體   English   中英

如何從 React JS 的 react 項目的公共目錄中的文件中讀取 xml?

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

在我的反應項目公共文件夾中,我有一個名為mySurvey.xml的文件,我想在我的 src 目錄中讀取該文件,因此為簡單起見,我嘗試在 app.js 中讀取它

在此處輸入圖像描述

因此,在我的 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

這會加載 html 頁面並且不會放棄 xml 數據

請指導我的方法是正確的還是有更好的方法!!

注意:- 公用文件夾中有很多 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 默認無法解析 xml。 因此,我使用 DOMParser 將字符串解析為 XML object。 一旦您獲得 xml object,您就可以將其存儲在您的 state 中並根據需要進行操作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM