This tutorial shows examples to read the XML file into a javascript object and write to XML file in NodeJS.

In Nodejs Environment, There are multiple npm libraries for parsing XML file format.

This example uses the fast-xml-parser npm module.

First, Install a library in the Project terminal

npm install fast-xml-parser

Parse XML file into a javascript object

Let’s create a users.xml file.

<users>
  <user >
    <id>1</id>
    <name>john</name>
    <!-- name of employee -->
    <salary>5000</salary>
    <!-- salary of employee -->
  </user>
  <user >
    <id>2</id>
    <name>Eric</name>
    <salary>3000</salary>
  </user>
  <user>
    <id>3</id>
    <name>Mark</name>
    <salary>5100</salary>
  </user>
</users>

Here is an example of reading xml file, to validate its content.

const fs = require('fs');
const { XMLParser, XMLBuilder, XMLValidator} = require("fast-xml-parser");

const parser = new XMLParser();

// Read XML content from a file
fs.readFile('users.xml', 'utf-8', (error, data) => {
  if (err) {
    console.error('Failed to read XML file:', error);
    return;
  }
  // Parse the data into an object
  let xmlJsonObj = parser.parse(data);
  console.error(xmlJsonObj.users);

  // Validate xml data
  const result = XMLValidator.validate(data, {
    allowBooleanAttributes: true
});
console.log(result) // return true

});

// Validation Failure
const xmlData = `<users><user></users>`;
const result1 = XMLValidator.validate( xmlData, {
  unpairedTags: ["extra"]
});
console.log(result1)// throws an error

In this example, it does the following things.

  • Parse XML file
  • Validate whether XML content is valid or not

First, Import required classes using require. Next, read the XML file using fs.readFile() that takes the file(users.xml), and calls back the function of (error, data) parameters.

  • if an error object is present, return with logging an error
  • else, the xml file is read into a data variable.
  • Create an parser(new XMLParser()), XMLParser is from fast-xml-parser library.
  • The parse method of this parser takes XML content variable, and Convert to a javascript object(xmlJsonObj)
  • Prints an object.
{
  user: [
    { id: 1, name: 'john', salary: 5000 },
    { id: 2, name: 'Eric', salary: 3000 },
    { id: 3, name: 'Mark', salary: 5100 }
  ]
}
  • you can access individual elements using dot notation(xmlJsonObj.users)

To validate XML content, use the XMLValidator.validate method to take XML content and options object, which Returns true, if XML content is valid, else returns an error

The second example missing the end tag and throws an error with InvalidTag.

{
  err: {
    code: 'InvalidTag',
    msg: "Expected closing tag 'user' (opened in line 1, col 8) instead of closing tag 'users'.",
    line: 1,
    col: 14
  }
}

Write to xml file in NodeJS

This example converts a javascript object(JSOn) into XML content and writes it to an XML file.

const { XMLParser, XMLBuilder, XMLValidator } = require("fast-xml-parser");
const fs = require("fs");
// options for XML builder
const options = {
  processEntities: false,
  format: true,
  ignoreAttributes: false,
};
// javascript object to convert to XML
const xmlObject = {
  user: [
    { id: 1, name: "john", salary: 5000 },
    { id: 2, name: "Eric", salary: 3000 },
    { id: 3, name: "Mark", salary: 5100 },
  ],
};

const builder = new XMLBuilder(options);
const xmlContent = builder.build(xmlObject);
// Writes to xml file
fs.writeFile("result.xml", xmlContent, (error) => {
  if (err) {
    console.error("Failed to write XML file:", error);
  } else {
    console.log("XML file created.");
  }
});

In this example,

  • First, Import all required classes from a given module
  • create an XMLBuilder object, takes options object that contains format:true optional for pretty print XML content
  • Declare a JSON object with data
  • pass the data to the builder.build() method, which converts JSON to XML Content String.
  • use fs.writeFile() to write XML string into a file if there are no errors.
  • On running the above code, It generates an XML file from a javascript object.