This tutorial help to nodejs xml parser using xmlbuilder2. We’ll use fs
module to read and write file in nodejs.
We’ll convert the XML file into JSON and iterate over the data. We’ll add nodes and attribute using JSON data. Finally, convert JSON data into XML string and save it into the file.
I have already created a tutorial Create XML File Using Nodejs xmlbuilder2.
What’s xmlbuilder2
xmlbuilder2 is a wrapper around a DOM implementation that includes chainable functions to make it easier to generate complicated XML documents. Function chaining naturally follows the structure of an XML document because it is a tree of nodes, resulting in more understandable source code.
Popular Nodejs XML Parser
We’ll look at several real-world XML use cases in this article, using some of the most popular npm packages, such as:
How To Parse XML in Nodejs
Let’s parse a XML file using xmlbuilder2. We’ll convert an XML into JSON data then modify data and again generate XML file.
We’ll cover following topic’s here:
- Parse XML to JSON
- Created a new node and attribute using json
- Updated xml json data
- Convert JSON into xml string
- Save xml data into the file
Let’s create a nodejs sample project into the nodejs workspace folder: D:\workflow_nodejs\xml-parser, create two files here:
– server.js
– this file will have logic here
– default.js
– This is ample xml file that ll use for parse.
cd
into the xml-parser folder:
Install Dependencies
You can install xmlbuilder2, xml2js and fs npm packages by running the following command:
npm install xmlbuilder2 --save npm install fs --save npm install xml2js --save
Let’s take a sample XML file, and write the below content into the default.xml
file.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Javascript async="false" continueOnError="false" enabled="true" timeLimit="200" name="post-request"> <DisplayName>post-request</DisplayName> <Properties/> <ResourceURL>jsc://post-request.js</ResourceURL> </Javascript>
How To Parse XML in JSON
Let’s parse an XML file and parse data in JSON format.
const xml2js = require('xml2js'); const fs = require('fs'); const parser = new xml2js.Parser({ explicitArray: true }); var filePath = 'default.xml'; fs.readFile(filePath, function(err, data) { parser.parseString(data, function(err, result) { console.log(result) }); });
Output:
{ Javascript: { '$': { async: 'false', continueOnError: 'false', enabled: 'true', timeLimit: '200', name: 'post-request' }, DisplayName: [ 'post-request' ], Properties: [ '' ], ResourceURL: [ 'jsc://post-request.js' ] } }
How To Access Node and Attribute
You can access node as like json object:
fs.readFile(filePath, function(err, data) { parser.parseString(data, function(err, result) { console.log(result.Javascript.DisplayName); console.log(result.Javascript.$.timeLimit); }); });
Output:
[ 'post-request' ] 200
How To update an XML File Using JSON
This XML tutorial help to update an existing XML using nodejs. We’ll add a new node with some properties in JSON data.
const xml2js = require('xml2js'); const fs = require('fs'); const parser = new xml2js.Parser({ explicitArray: true }); var filePath = 'default.xml'; fs.readFile(filePath, function(err, data) { parser.parseString(data, function(err, result) { let f1 = {"User": {"$":{"name":"Adam"},"Address":{"Street":"123 park avenue"}}} result.Javascript.Person = f1; console.log(result); }); });
JSON Output:
{ Javascript: { '$': { async: 'false', continueOnError: 'false', enabled: 'true', timeLimit: '200', name: 'post-request' }, DisplayName: [ 'post-request' ], Properties: [ '' ], ResourceURL: [ 'jsc://post-request.js' ], Person: { User: [Object] } } }
Convert JSon data into XML String
We have JSON data that is converted from an XML file, let’s convert it into XML string data using xmlbuilder2.
const { create } = require('xmlbuilder2'); const xml2js = require('xml2js'); const fs = require('fs'); const builder = new xml2js.Builder(); const parser = new xml2js.Parser({ explicitArray: true }); var filePath = 'default.xml'; fs.readFile(filePath, function(err, data) { parser.parseString(data, function(err, result) { let f1 = {"User": {"$":{"name":"Adam"},"Address":{"Street":"123 park avenue"}}} result.Javascript.Person = f1; let xml_string = builder.buildObject(result); console.log(xml_string); }); });
Output:
<Javascript async="false" continueOnError="false" enabled="true" timeLimit="200" name="post-request"> <DisplayName>post-request</DisplayName> <Properties/> <ResourceURL>jsc://post-request.js</ResourceURL> <Person> <User name="Adam"> <Address> <Street>123 park avenue</Street> </Address> </User> </Person> </Javascript>
Update an XML FIle Using Nodejs
This tutorial help to update an XML file using xmlbuilder package.
Save XML String into a File
We have created an XML string in the above code, let’s save it into the XML file. we’ll use fs
module writeFile()
method to save file into the file system.
const { create } = require('xmlbuilder2'); const xml2js = require('xml2js'); const fs = require('fs'); const builder = new xml2js.Builder(); const parser = new xml2js.Parser({ explicitArray: true }); var filePath = 'default.xml'; fs.readFile(filePath, function(err, data) { parser.parseString(data, function(err, result) { let f1 = {"User": {"$":{"name":"Adam"},"Address":{"Street":"123 park avenue"}}} result.Javascript.Person = f1; let xml_string = builder.buildObject(result); fs.writeFile(filePath, xml_string, function(err, data){ if (err) console.log(err); }); }); });
Output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Javascript async="false" continueOnError="false" enabled="true" timeLimit="200" name="post-request"> <DisplayName>post-request</DisplayName> <Properties/> <ResourceURL>jsc://post-request.js</ResourceURL> <Person> <User name="Adam"> <Address> <Street>123 park avenue</Street> </Address> </User> </Person> </Javascript>