Convert string to xml and xml to string using javascript

Convert string to xml and xml to string using javascript

01 Feb 2024
7 min read
Learn via Video Course & by Doing Hands-on Labs

JavaScript For Beginners Free Course

Convert String to XML and XML to String using Javascript: An Overview

Hello there! Have you ever wanted to know how to switch between text and XML in JavaScript? It's so easy! You can easily convert a string to XML and vice versa. You can transform your data from text to structured XML format with just a few lines of code. Let's get into the JavaScript Tutorial magic

Converting String to XML

Converting a string to XML involves converting unstructured text data into a structured manner using XML tags and attributes.

Methods for Converting a String to XML Using JavaScript

Following are the Methods for Converting a String to XML Using Javascript

DOMParser Method

The DOMParser object has a method called parseFromString that parses a string that contains either HTML or XML and produces a document object (HTMLDocument or XMLDocument). This allows you to directly load and manipulate XML data within your JavaScript code.

Example of DOMParser Method

const xmlString = "<root><element>data</element></root>";const xmlDoc = new DOMParser().parseFromString(xmlString, "text/xml");

console.log(xmlDoc.documentElement.textContent); // Output: data

xmlString is defined in this code as a valid XML document having a single element "data" inside a "root" element. It then converts xmlString into an XML document object and obtains the text content of the "data" element, which is printed as "data."

XMLHttpRequest Object

The XMLHttpRequest object communicates with a server by sending HTTP requests (GET, POST, etc.) and receiving replies (text, JSON, XML). While it cannot directly convert text to XML, it can retrieve an XML document from a server and parse it into an XML object using DOMParser.

Read More: 50+ Javascript Interview Questions and Answers

const xhr = new XMLHttpRequest();"GET", "", true); // Replace URL with your XML filexhr.onload = () => { if (xhr.status === 200) {  const xmlDoc = new DOMParser().parseFromString(xhr.responseText, "text/xml");  // Access XML data using xmlDoc object } else {  console.error("Error fetching XML"); }};


This code initially generates and configures an XMLHttpRequest to retrieve an XML file from a given URL. It creates an onload handler that, if successful, parses the obtained XML into a document object for further processing.

Third-Party Libraries

Parses XML texts or files into JavaScript objects & vice versa, allowing for simple XML data processing and serialization.

Example of Third-Party Libraries

const xmlString = "<data><name>John</name><age>30</age></data>";const jsObject = xml2js.parseString(xmlString, {explicitArray: false});

console.log(; // Output: John

Using xml2js, the code converts an XML string with "data" and its child parts into a JavaScript object. It then outputs "John" from the "name" value within the parsed "data" object.

Converting XML to String

The process of converting XML to a string involves converting structured data encoded in XML format into a plain text string.

Methods for Converting XML to String

Following are the Methods for Converting XML to String

XMLSerializer Method

In JavaScript, the XMLSerializer object has a serializeToString method that converts a DOM node (an XML document or any element within it) into its equivalent XML string representation.

Read More: Javascript Developer Salary in India

Example of XMLSerializer Method

// Sample XML documentconst xmlString = '<book><title>Moby Dick</title><author>Herman Melville</author></book>';// Parse the XML string into a DOM documentconst xmlDoc = new DOMParser().parseFromString(xmlString, 'text/xml');// Create an XMLSerializer objectconst serializer = new XMLSerializer();// Convert the document to a stringconst serializedString = serializer.serializeToString(xmlDoc);

console.log(serializedString); // Output: `<book><title>Moby Dick</title><author>Herman Melville</author></book>`

DOMParser is used to convert the XML string (xmlString) into a DOM document (xmlDoc). Then, with the document, we build an XMLSerializer object and call its serializeToString method, capturing the resulting XML string in a serialized string.

String Concatenation

String concatenation is the process of bringing together numerous strings. In this case, manually constructing the XML string would entail looping through elements and attributes, adding tags, content, and separators such as <and >.

Example of String Concatenation

// NOT recommended! Error-prone and fragile
const xmlString = "";
xmlString += "<book>";
xmlString += "<title>Moby Dick</title>";
xmlString += "<author>Herman Melville</author>";
xmlString += "</book>";

console.log(xmlString); // Output: "<book><title>Moby Dick</title><author>Herman Melville</author></book>"

This code creates an XML string by concatenating tags and content, avoiding safer alternatives such as XMLSerializer. While it works for simple scenarios, it is prone to errors owing to manual formatting and escaping, and it is unstable for complex structures.

JavaScript provides several methods for converting between text and XML. DOMParser converts text to XML objects, whereas XMLSerializer converts XML back to text. The server-side XML fetching is handled via XMLHttpRequest. Consider using third-party libraries for complex structures. String concatenation, while inefficient, is sufficient for simple cases. Choose a method depending on your requirements and level of complexity.


Q1. In JavaScript, how do you convert XML to a string?

toXMLString() method transforms an XML object into an XML string. To move across an XML document, you must use the other XML get methods.

Q2. How can XML data be converted to a string?

We begin by creating a TransformerFactory and a Transformer for XML transformation. The modified XML is then stored in text form using a StringWriter. The transform() method then modifies the XML Document, which we may store into the result string using stringWrite.

Q3. What is the tool for converting XML to strings?

XML Stringify is a simple utility for converting XML to XML Strings and escaping special characters.

Q4. What JavaScript conversion method is there for a string data type?

We can explicitly convert values of Boolean or numeric data types to string values using String() or n. toString() to guarantee that our code operates as expected.

Q5. What does XML mean in JavaScript?

XML (Extensible Markup Language) is a markup language that is similar to HTML but lacks predefined tags. Instead, you create your tags that are tailored to your requirements. This is an effective method for storing data in a format that can be stored, found, and shared.

Take our Javascript skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.


Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Azure DevOps Certification Training Course Jun 01 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Data Structures and Algorithms Training Jun 04 TUE, FRI
Filling Fast
08:30PM to 10:00PM (IST)
Get Details
ASP.NET Core Certification Training Jun 14 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
ASP.NET Core (Project) Jun 22 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this