Search code examples
reactjsxml-to-json

How to convert XML to JSON in reactjs?


How to convert XML document to JSON using reactjs? I got response shown down below. I tried a lot of things and still nothing.

import React, { useEffect } from 'react'

function Api() {

    useEffect(() => {
        fetch("/author/list/18541?format=xml&key=TftQypHkudfH0VZcukEWtg")
            .then(res => res.text())
            .then(data => {
                let parser = new DOMParser()
                let xmlDoc = parser.parseFromString(data, 'text/xml')
                console.log(xmlDoc)
            })
            .catch(err => console.log(err));
    }, [])

    return (
        <div></div>
    )
}

export default Api

enter image description here


Solution

  • Since you are using react. I searched npm for XML react and found react-xml-parser.

    First you will need to install react-xml-parser

    $ npm install react-xml-parser
    

    Then you will be able to use it in your react app.

    import React, { useEffect } from 'react'
    import XMLParser from 'react-xml-parser';
    
    function Api() {
    
        useEffect(() => {
            fetch("/author/list/18541?format=xml&key=TftQypHkudfH0VZcukEWtg")
                .then(res => res.text())
                .then(data => {
                    var xml = new XMLParser().parseFromString(data); 
                    console.log(xml)
                })
                .catch(err => console.log(err));
        }, [])
    
        return (
            <div></div>
        )
    }
    
    export default Api