@giovanny.lueilwitz
To read an XML file in React.js, you can make use of the fetch()
function provided by the browser's window object. Here's an example of how you can accomplish this:
1
|
npm install xml2js |
1 2 |
import { useEffect, useState } from 'react'; import xml2js from 'xml2js'; |
1 2 3 4 5 6 7 8 9 10 11 |
const readXmlFile = async () => { const response = await fetch('path/to/xml/file.xml'); const xmlText = await response.text(); // Convert XML to JSON const parser = new xml2js.Parser(); const parsedXml = await parser.parseStringPromise(xmlText); // Access the XML data as JSON console.log(parsedXml); }; |
1 2 3 4 5 6 7 8 9 10 11 |
const ExampleComponent = () => { useEffect(() => { readXmlFile(); }, []); return ( <div> {/* Your JSX code */} </div> ); }; |
Here, we use the useEffect()
hook to call the readXmlFile()
function when the component is mounted. Adjust the fetch()
function to specify the correct path to your XML file.
The parsedXml
variable will contain the XML data parsed into a JSON format, which you can then access and display in your React component as needed.