JavaScript: Parsing XML in the Browser

Image for post
Image for post

XML is not my favorite data exchange format, but sometimes you have no choice. So if it comes to the question how to handle those data in JavaScript, I first want to use an existing npm module that flies around in the www. But on second sight I found a even simpler solution, that does not need anything, except the browser who is already there.

The browser has a parser build in, who can also parse given XML data. Let’s try to use it.

The first step towards my content goes through a request I have done with fetch.

const result = await fetch(requestUrl)
const xml = await result.text()

The next an almost final step, easy as is, was to parse the result.

const domParser = new DOMParser()
const xmlDocument = domParser.parseFromString(xml, 'text/xml')

And then we are almost there. The last step is to get something out of this DOM nodes, what can easily be used in JavaScript: an Object.


export default from './xml-parser'


const api = {
xmlToJson (xml) {
let jsonData = {}
if (xml.nodeType === 1) {
if (xml.attributes.length > 0) {
jsonData.attributes = {}
for (let j = 0; j < xml.attributes.length; j++) {
const attribute = xml.attributes.item(j)
jsonData.attributes[attribute.nodeName] = attribute.nodeValue

const textNodes = [] => node.nodeType === 3)
if (xml.hasChildNodes() && xml.childNodes.length === textNodes.length) {
jsonData = [], node) => text + node.nodeValue, '')
} else if (xml.hasChildNodes()) {
for (let i = 0; i < xml.childNodes.length; i++) {
const item = xml.childNodes.item(i)
const nodeName = item.nodeName.replace(':', '_')
if (nodeName !== '#text') {
if (typeof jsonData[nodeName] === 'undefined') {
jsonData[nodeName] = this.xmlToJson(item)
} else {
if (typeof jsonData[nodeName].push === 'undefined') {
const old = jsonData[nodeName]
jsonData[nodeName] = []
return jsonData

export default api

And that’s it.

See You

Developer since the 80'th, working at Forschungszentrum Jülich ( …

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store