Blog.

How to fetch XML with Fetch API

Cover Image for How to fetch XML with Fetch API

Currently, Fetch API doesn't support fetching XML natively (so no native XML parser), but there are workarounds.

Currently, Fetch API doesn't support fetching XML natively (so no native XML parser), but there are workarounds.

We can use the built-in text() parser and parse the resulted strings into XML using a custom XML parser. In the example below I choose xml2js parser, I recommend reading the docs first.

import fetch from 'isomorphic-unfetch'
import xml2js from 'xml2js'

const parser = new xml2js.Parser()

async function getXMLfromURL(url) {
	try {
		const response = await fetch(url)
		const content = await response.text()
		const data = await parser.parseStringPromise(content)
	
		return data
	} catch (e) {
		console.log({e})
	}
}

getXMLfromURL('https://example.com/api')

If you want to run the following code in Node.js easily (with ES modules supported) I recommend using esm package like so:

$ npm i esm --save-dev

And you either run your index.js file directly from node:

$ node -r esm index.js

Or you can create a script inside package.json file that does the same thing

"scripts": {
	"dev": "node -r esm index.js"
}

Further reading

Daniel Turuș

@danielturus

Hi! My name is Daniel and I am a Full-stack JavaScript developer.

If you like my material, please consider following me on Twitter to get notified when new posts are published, ask me a question and stay in touch.