How To Convert String To Xml In Javascript

Converting a string to XML is a common task when working with web services or any other data exchange format that requires XML structure. In this blog post, we will discuss how to convert a string to an XML document with a simple JavaScript function using the DOMParser API.


Before diving into the implementation, make sure your environment supports the DOMParser API. DOMParser is available in almost all modern browsers, including:

  • Google Chrome
  • Firefox
  • Safari
  • Microsoft Edge (version 12 and above)
  • Internet Explorer (version 9 and above with some limitations)

If you are targeting an older browser that does not support DOMParser, you may need to use a third-party library or a different approach to parse the XML string.

Convert String to XML using DOMParser

The DOMParser API allows you to parse a string containing XML or HTML content and convert it into a DOM (Document Object Model) tree. The parseFromString method of the DOMParser object accepts two arguments:

  • The XML string to parse
  • A string that represents the content type (either “text/xml” or “application/xml” for XML parsing)

Here is a simple function that demonstrates how to use the DOMParser API to convert a string to an XML document:

    function convertStringToXML(xmlString) {
        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(xmlString, "text/xml");
        return xmlDoc;

To use this function, simply call it with your XML string as the argument:

    const xmlString = '<root><element>content</element></root>';
    const xmlDoc = convertStringToXML(xmlString);

This will output the following XML document:


Error Handling

If the input string is not a valid XML, the DOMParser will generate an XML document containing a <parsererror> element. To check for parsing errors, you can search for this element in the resulting XML document:

    function convertStringToXMLWithErrorHandling(xmlString) {
        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(xmlString, "text/xml");

        if (xmlDoc.getElementsByTagName("parsererror").length &gt; 0) {
            throw new Error("Error parsing XML string");

        return xmlDoc;

Now, if you call this function with an invalid XML string, it will throw an error:

    const invalidXml = '<root><element>content</element>';
    try {
        const xmlDoc = convertStringToXMLWithErrorHandling(invalidXml);
    } catch (error) {
        console.error(error.message); // "Error parsing XML string"


In this blog post, we have seen how to convert a string to an XML document using the DOMParser API in JavaScript. This is a simple and efficient way to handle XML data, especially when working with web services or other data exchange formats that require XML structure. Remember to always check for browser compatibility and handle errors properly to ensure a smooth user experience.