1

I am trying to parse the input xml data to json in react with the help of xml2js.

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

function Parser() {
  const [xmlData, setXmlData] = useState({});
  let parser = new xml2js.Parser();
  parser.parseString(
    `<email>
       <to>Test</to>
       <from>Test1</from>
       <heading>Test email</heading>
       <body>Email regards to xml data parsing in React</body>
       </email>`,
    function (err, result) {
      console.log(result);
      if (result) {
        setXmlData(result);
        return;
      }
      return;
    }
  );
  return (
    <div>
      Parse XML using ReactJs
      {JSON.stringify(xmlData)}
    </div>
  );
}

export default Parser;

But I am getting unlimited re render error. Can anyone help on this ?

Thanks in advance

1 Answers1

2

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>`}
/>
AKX
  • 152,115
  • 15
  • 115
  • 172
  • Hi thanks for replying. Is there any other way? Currently its displaying as {"email":{"to":["Test"],"from":["Test1"],"heading":["Test email"],"body":["Email regards to xml data parsing in React"]}} but i want as {"email":{"to": "Test","from":"Test1","heading":"Test email","body":"Email regards to xml data parsing in React"}} without the square braces –  Aug 02 '21 at 13:08
  • That's up to the `xml2js` library you're using. It [apparently supports a `explicitArray` option](https://www.npmjs.com/package/xml2js#options) to control that behavior. Try `new xml2js.Parser({explicitArray: false})` – AKX Aug 02 '21 at 13:09
  • Thanks you so much @AKX –  Aug 02 '21 at 13:19
  • Hi Akx, can u look onto https://stackoverflow.com/questions/68622784/how-to-convert-xml-data-to-json-with-fast-xml-parser –  Aug 02 '21 at 13:52