2

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

1 Answer 1

5

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

1 Comment

when I install it, I get error about react-xml-parser, so I found this, very similar solution: var XMLParser = require('react-xml-parser') var xml = new XMLParser().parseFromString(data) console.log(xml)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.