Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Convert string to xml and xml to string using javascript

Convert string to xml and xml to string using javascript

01 Feb 2024
Intermediate
28.9K Views
7 min read
Learn with an interactive course and practical hands-on labs

Free Javascript Course: Learn Javascript In 21 Days

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();xhr.open("GET", "https://example.com/data.xml", 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"); }};

xhr.send();

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(jsObject.data.name); // 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.
Summary

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.

FAQs

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

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.


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


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.


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.

GET FREE CHALLENGE

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this