How to Parse Xml File in React

How to read xml file(data.xml) in React js?

to read a local file you have two options either you can use XMLHttpRequest or axios.
Using XMlHttpRequest:

import XMLData from '../../xmldata/list.xml';

var rawFile = new XMLHttpRequest();
rawFile.open("GET", XMLData, false);
rawFile.onreadystatechange = () => {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var xmlasstring = rawFile.responseText;
console.log('Your xml file as string', xmlasstring)
}
}

I would recommend using axios bcz it is more convenient and better option when working with Reactjs
Using axios:

import XMLData from '../../xmldata/list.xml';

axios.get(XMLData, {
"Content-Type": "application/xml; charset=utf-8"
})
.then((response) => {
console.log('Your xml file as string', response.data);
});

Now after getting your xml you can make object or json if you want by using npm packages like react-xml-parser, xml2js. I would recommend using xml2js it's nice. And I believe now you can also send 'POST' request in order to update your xml if you want.

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

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

How to parse input xml data to json in react with xml2js?

Since parseString is an asynchronous API, you will need to call it in an useEffect hook with the input data set as a dependency to avoid it being re-re-re-re-...-called on each render.

I also moved the input data to a prop here, for reusability.

import React, { useState } from "react";
import xml2js from "xml2js";

function Parser({ inputData }) {
const [xmlData, setXmlData] = React.useState(null);
React.useEffect(() => {
const parser = new xml2js.Parser();
parser.parseString(inputData, function (err, result) {
setXmlData(result);
});
}, [inputData]);
return (
<div>
Parse XML using ReactJs
{JSON.stringify(xmlData)}
</div>
);
}

export default Parser;
<Parser inputData={`<email>
<to>Test</to>
<from>Test1</from>
<heading>Test email</heading>
<body>Email regards to xml data parsing in React</body>
</email>`}
/>

React js, how to use xml as your html design

Use DOMParser to parse XML or HTML source code from a string into a DOM Document. The get the desired node and append it to some part of your document:

const appendToNode = (node, content) => {
node.innerHTML += content;
};

useEffect(() => {
const DOMParse = new DOMParser();
let xmlDoc;
axios
.get(
'https://uhf.microsoft.com/en-US/shell/xml/MSIrelandsFuture?headerId=MSIrelandsFutureHeader&footerid=MSIrelandsFutureFooter',
{
'Content-Type': 'application/xml; charset=utf-8'
}
)
.then(response => {
xmlDoc = DOMParse.parseFromString(response.data, 'text/xml');
appendToNode(
ref.current //--> some node in your document
xmlDoc.querySelector('headerHtml').textContent //--> do the same with the rest of the nodes
);
})
.catch(err => console.log(err));
}, []);

Working example

I recommend you to use html-react-parser library to transform the HTML string into a JSX element.

How to deal with xml file in next js?

Since you are using API Route, these will be handled on the server-side, which means you are able to use Node APIs to read files and parse with xml2js lib

const parseString = require('xml2js').parseString;
const fs = require('fs');
const path = require('path');

export default (req, res) => {
const data = fs.readFileSync(path.join(process.cwd(), 'note.xml'));
parseString(data, function (err, result) {
console.log(result);
res.status(200).json({ result });
});
};

https://nextjs-gkkygf--3000.local.webcontainer.io/api/xml

Full Stackblitz example



Related Topics



Leave a reply



Submit