Open In App

How to Create XML in JavaScript ?

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, XML documents can be created using various approaches. You can define elements, attributes, and content to structure the XML data, and then serialize it into a string for use or storage.

There are several approaches to creating XML in JavaScript which are as follows:

Using DOMParser and XMLSerializer

In this approach, we are using the DOMParser and XMLSerializer from the ‘xmldom’ package to create an XML document in JavaScript. First, we parse an empty XML string to initialize the document, then we create elements like ‘Language’ and ‘Topic’ and append them to the root element. Finally, we serialize the document to a string and use the ‘pretty-data’ package’s pd.xml function to format the XML output.

Installtion Syntax:

npm install xmldom pretty-data

Example: The below example uses DOMParser and XMLSerializer to Create XML in JavaScript.

JavaScript
const {
    DOMParser,
    XMLSerializer
} = require('xmldom');
const {
    pd
} = require('pretty-data');
let xmlDoc = new DOMParser()
    .parseFromString('<GeeksforGeeks></GeeksforGeeks>', 'text/xml');
let rootEle = xmlDoc
    .documentElement;
let lElement = xmlDoc
    .createElement('Language');
lElement.textContent = 'JavaScript';
rootEle.appendChild(lElement);
let childEle = xmlDoc
    .createElement('Topic');
childEle.textContent = 'Creating XML in JavaScript';
rootEle.appendChild(childEle);
let xmlString = new XMLSerializer()
    .serializeToString(xmlDoc);
let res = pd
    .xml(xmlString);
console.log(res);

Output:

<GeeksforGeeks>
<Language>JavaScript</Language>
<Topic>Creating XML in JavaScript</Topic>
</GeeksforGeeks>

Using xmlbuilder2 Library

In this approach, we are using the xmlbuilder2 library to create an XML document in JavaScript. We begin by specifying the encoding and version, then add elements like ‘GeeksforGeeks’ and ‘Language’ with their respective content, ending with pretty-printing the XML output using pretty-data.

Installation Syntax:

npm install xmlbuilder2 pretty-data

Example: The below example uses xmlbuilder2 to Create XML in JavaScript.

JavaScript
const {
    create
} = require('xmlbuilder2');
const {
    pd
} = require('pretty-data');
const xml = create({
    encoding: 'UTF-8',
    version: '1.0'
})
    .ele('GeeksforGeeks')
    .ele('Language', 'JavaScript')
    .up()
    .ele('Topic', 'Creating_XML_in_JavaScript')
    .end({
        prettyPrint: true
    });
let res = pd.xml(xml);
console.log(res);

Output:

<?xml version="1.0" encoding="UTF-8"?>
<GeeksforGeeks>
<JavaScript
xmlns="Language"/>
<Creating_XML_in_JavaScript
xmlns="Topic"/>
</GeeksforGeeks>


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads