Leonidas-from-XIV / node-xml2js

XML to JavaScript object converter.
MIT License
4.87k stars 601 forks source link

using xml2js with fs in React JS #590

Closed Sayyamabbasi786 closed 3 years ago

Sayyamabbasi786 commented 3 years ago

I am using xml2js with fs in React JS with it is throwing error of node but I am using React. Is there any way to read XML, Please anyone can provide me an example of how to do in react.

fiso commented 3 years ago

You can't use the fs module in a browser environment (which is where I assume you are, since you're using React). You're going to have to either have the xml data stored as a string in your javascript, or fetch it from some http endpoint and then parse it.

Example:

const xmlFileUrl = "https://somedomain.com/somefile.xml";

const XmlComponent = () => {
    useEffect(() => {
        async function loadXML() {
            const result = await fetch(xmlFileUrl);
            if (!result.ok) {
                console.error("Error fetching file");
                return;
            }

            const xml = await result.text();
            parseString(xml, { explicitArray: false }, function (error,result) {
                console.dir(result);
            });
        }

        loadXML();
    }, []);

    return <div />;
};
Sayyamabbasi786 commented 3 years ago

@fiso I found the solution very next day, we don't need either to quote xml in string because it is not a good practice. I had the xml file in folder so what I did ?? I fetch the data using axios just by passing the path of file and then parse it with xml2js parser and huraaah it worked! ;)