# How to edit an XML file with Node.js

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Apr 16, 2020, updated Oct 1, 2022. Topics: Node.js.
Canonical URL: https://attacomsian.com/blog/nodjs-edit-xml-file

> A quick article on learning how to update XML file contents using Node.js.

In an [earlier article](https://attacomsian.com/blog/nodejs-convert-xml-to-json), 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:

```bash
$ node install xml2js --save
```

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

<p class="file-desc"><span>index.js</span></p>

```javascript
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](https://attacomsian.com/blog/reading-writing-files-nodejs#reading-from-files) from the disk and prints it on the console. Here is an example of an XML file that needs to be updated:

<p class="file-desc"><span>databases.xml</span></p>

```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:

```javascript
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:

```json
{
    "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`:

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

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

```javascript
// 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:

```javascript
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:

```javascript
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](https://attacomsian.com/blog/nodejs-convert-xml-to-json)
