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 Answer 1

3

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>`}
/>
Sign up to request clarification or add additional context in comments.

4 Comments

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
That's up to the xml2js library you're using. It apparently supports a explicitArray option to control that behavior. Try new xml2js.Parser({explicitArray: false})
Thanks you so much @AKX

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.