How to edit an XML file with Node.js

In an earlier article, we looked at converting an XML file to a JSON object in Node.js by using the open-source xml2js module. Today, you'll learn how to edit an XML file with Node.js.

Basic Setup

First of all, add the xml2js module to your Node.js application by typing the following command in your terminal:

$ node install xml2js --save

Next, create a new JavaScript file called index.js with the following content:

index.js

const fs = require('fs')

// read XML file
fs.readFile('databases.xml', 'utf-8', (err, data) => {
  if (err) {
    throw err
  }
  console.log(data)
})

The above code reads an XML file from the disk and prints it on the console. Here is an example of an XML file that needs to be updated:

databases.xml

<?xml version="1.0" encoding="UTF-8" ?>
<databases>
    <database>
        <name>MySQL</name>
        <type>RDBMS</type>
    </database>
    <database>
        <name>MongoDB</name>
        <type>NoSQL</type>
    </database>
    <database>
        <name>Neo4j</name>
        <type>Graph DB</type>
    </database>
</databases>

Convert XML to JSON

Since we read the XML file into a string, we can easily convert it into a JSON object using the xml2js.parseString() method.

Let us update the above example code to include XML parsing to JSON:

const fs = require('fs')
const xml2js = require('xml2js')

// read XML file
fs.readFile('databases.xml', 'utf-8', (err, data) => {
  if (err) {
    throw err
  }

  // convert XML data to JSON object
  xml2js.parseString(data, (err, result) => {
    if (err) {
      throw err
    }

    // print JSON object
    console.log(JSON.stringify(result, null, 4))
  })
})

If you run the above code, you should see the following JSON object printed out on the console:

{
    "databases": {
        "database": [
            {
                "name": [
                    "MySQL"
                ],
                "type": [
                    "RDBMS"
                ]
            },
            {
                "name": [
                    "MongoDB"
                ],
                "type": [
                    "NoSQL"
                ]
            },
            {
                "name": [
                    "Neo4j"
                ],
                "type": [
                    "Graph DB"
                ]
            }
        ]
    }
}

Editing the XML

Editing a JSON object in JavaScript is incredibly straightforward. Let us replace the Neo4j database with another graph database called ArangoDB:

// replace `Neo4j` with `ArangoDB`
result.databases.database[2].name = 'ArangoDB'

You can also add a new database to the existing databases list:

// add a new database to list
const postgres = {
  name: 'PostgreSQL',
  type: 'RDBMS'
}

result.databases.database.push(postgres)

After the above modifications, our updated example code looks like the below:

const fs = require('fs')
const xml2js = require('xml2js')

// read XML file
fs.readFile('databases.xml', 'utf-8', (err, data) => {
  if (err) {
    throw err
  }

  // convert XML data to JSON object
  xml2js.parseString(data, (err, result) => {
    if (err) {
      throw err
    }

    // replace `Neo4j` with `ArangoDB`
    result.databases.database[2].name = 'ArangoDB'

    // add a new database to list
    const postgres = {
      name: 'PostgreSQL',
      type: 'RDBMS'
    }

    result.databases.database.push(postgres)

    // print JSON object
    console.log(JSON.stringify(result, null, 4))
  })
})

Convert JSON to XML

Now that we have successfully modified our JSON object, we can convert it back to an XML string and finally write it to a file:

const fs = require('fs')
const xml2js = require('xml2js')

// read XML file
fs.readFile('databases.xml', 'utf-8', (err, data) => {
  if (err) {
    throw err
  }

  // convert XML data to JSON object
  xml2js.parseString(data, (err, result) => {
    if (err) {
      throw err
    }

    // replace `Neo4j` with `ArangoDB`
    result.databases.database[2].name = 'ArangoDB'

    // add a new database to list
    const postgres = {
      name: 'PostgreSQL',
      type: 'RDBMS'
    }

    result.databases.database.push(postgres)

    // convert SJON objec to XML
    const builder = new xml2js.Builder()
    const xml = builder.buildObject(result)

    // write updated XML string to a file
    fs.writeFile('new-databases.xml', xml, err => {
      if (err) {
        throw err
      }

      console.log(`Updated XML is written to a new file.`)
    })
  })
})

That's it. Run the above code, and you should see a new XML file generated with the updated XML within the same directory as your Node.js script file exists.

Read Next: How to convert XML to JSON in Node.js

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.