Editing XML Files With NodeJS Image Editing XML Files With NodeJS

XML files are still widely used in enterprise programs and being able to manipulate xml files can be incredibly important.

XML2JS Node Package

In this tutorial I’ll be demonstrating how you can easily manipulate XML files using the xml2js node package. This package is great due to the fact it reads in an xml string and converts it to a far easier to use json structure.

Reading in our XML File

Create a new js file and type the following:

1
2
3
4
5
6
7
var fs = require('fs');

fs.readFile('test.xml', 'utf-8', function (data, err){
    if(err) console.log(err);
    console.log(data);    
});       

Below you’ll find a sample xml file that we’ll be using:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <graph>
        <node>
            <name>Node 1</name>
            <weight>24</weight>
        </node>
        <node>
            <name>Node 2</name>
            <weight>18</weight>
        </node>
        <node>
            <name>Node 3</name>
            <weight>47</weight>
        </node>
        <node>
            <name>Node 4</name>
            <weight>58</weight>
        </node>
    </graph>
</root>

Converting Our XML Data to Json

Ok, so now that we’ve got the ability to read our xml files, we can then convert this to a far easier format to work with. The xml2js package is an excellent package that will take in any xml string and convert it to a json object. Again we can install this using the node package manager:

1
npm install xml2js --save-dev

Once this is installed, modify your existing code to use the parseString method like so:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
var fs = require('fs'),
    parseString = require('xml2js').parseString;

fs.readFile('test.xml', 'utf-8', function (err, data){
    if(err) console.log(err);
    // we log out the readFile results    
    console.log(data);
    // we then pass the data to our method here
    parseString(data, function(err, result){
        if(err) console.log(err);
        // here we log the results of our xml string conversion
        console.log(result); 
    });
});       

If you run this you should see our newly created JSON object printed out in the console.

Editing our New JSON Object

JSON object manipulation is incredibly in javascript. I’m not going to go into depth about how we can edit it but as a means of demonstrating how we can edit the xml I’m going to change the name of the weight of the first node in our xml file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
var fs = require('fs'),
    parseString = require('xml2js').parseString;

fs.readFile('test.xml', 'utf-8', function (err, data){
    if(err) console.log(err);
    // we log out the readFile results    
    console.log(data);
    // we then pass the data to our method here
    parseString(data, function(err, result){
        if(err) console.log(err);
        // here we log the results of our xml string conversion
        console.log(result); 
        // save our json to a variable
        var json = result;
        // edit the first node’s weight and set it to 99
        json.root.graph[0].node[0].weight = "99";
                  
    });
});       

Converting to XML and Writing to FIle

Now that we’ve successfully edited our json, we can then convert it back to xml and finally write it to a file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var fs = require('fs'),
    parseString = require('xml2js').parseString,
    xml2js = require('xml2js');

fs.readFile('test.xml', 'utf-8', function (err, data){
    if(err) console.log(err);
    // we log out the readFile results    
    console.log(data);
    // we then pass the data to our method here
    parseString(data, function(err, result){
        if(err) console.log(err);
        // here we log the results of our xml string conversion
        console.log(result); 
        
        var json = result;
        
        json.root.graph[0].node[0].weight = "99";
        
        // create a new builder object and then convert
        // our json back to xml.
        var builder = new xml2js.Builder();
        var xml = builder.buildObject(json);
        
        fs.writeFile('edited-test.xml', xml, function(err, data){
            if (err) console.log(err);
            
            console.log("successfully written our update xml to file");
        })
                  
    });
});       

Run this and you should see our newly created and updated xml within the same directory as your node script.

Was This Post Helpful?
Submit a PR: Edit on Github