How to convert a string to an XML Document in JavaScript?

Sometimes, we want to convert a string to an XML Document in JavaScript.

In this article, we’ll look at how to convert a string to an XML Document in JavaScript.

How to convert a string to an XML Document in JavaScript?

To convert a string to an XML Document in JavaScript, we can use the DOMParser constructor.

For instance, we write:

const xmlString = '<foo><bar>something</bar></foo>';
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "application/xml");
console.log(xmlDoc)

We create a new DOMParser instance.

And then we call parseFromString with the xmlString and the 'application/xml' MIME type to parse the string as XML.

Therefore, xmlDoc is an XML document converted from the string.

Conclusion

To convert a string to an XML Document in JavaScript, we can use the DOMParser constructor.