in this node tutorial, I’ll share a nodejs script to add and update a node in an XML file using nodejs. I am using nodejs fs
module to read an XML file.
I have already shared xml parsing in json usin nodejs and 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.
What’s Nodejs fs Module
The fs
module has a variety of helpful features for accessing and interacting with the file system.
It is not required to be installed. It can be utilized by just requiring it because it is part of the Node.js core:
var fs = require("fs")
Add A New Node in an XML FIle
We’ll create a new node in XML format and add it to an existing XML file.
Let’s create a deafult.xml
file and read this file using readFile()
method.
var filePath = `default.xml`; fs.readFile(filePath, function(err, data) { parser.parseString(data, function (err, result) { result.Rules = {"Rule": {"$":{"name":"custom_rule"},"Condition":"customErrorCode != null and customErrorMessage != ' '","Step":{"Name":"Custom-Response", "Condition":"customErrorCode != null and customErrorMessage != ' '"}}}; let xml = builder.buildObject(result); fs.writeFile(filePath, xml, function(err, data){ if (err) console.log(err); }); }); });
Update A Node Using Nodejs
Let’s update an existing node into an xml file. We’ll add properties and inner element in node using nodejs.
var filePath = `default.xml`; fs.readFile(filePath, function(err, data) { parser.parseString(data, function (err, result) { result.Rule[0] = {"API": {"$":{"name":"get data"},"Step":{"Name":"get-Response"}}}; let xml = builder.buildObject(result); fs.writeFile(filePath, xml, function(err, data){ if (err) console.log(err); }); }); });