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

Marina
  • 187
  • 1
  • 3
  • 19

1 Answers1

4

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
Joshua Rose
  • 370
  • 2
  • 10
  • 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)` – Marina Apr 24 '20 at 08:26