Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *