There are many ways to use node.js to convert XML to JSON. To date, one of the simplest involves an npm module called xml2js.

The basic wrapper code is:

var fs = require( 'fs' ),
    x2j = require( 'xml2js' );

var sInputFile = "books.xml;"

var p = new x2j.Parser();
var sXMLData = fs.readFileSync( sInputFile, 'utf8' );

p.parseString( sXMLData, function( err, result ) { 
   var s = JSON.stringify( result, undefined, 3 );
   console.log( "Result" + "\n", s, "\n" );
});

Here, the input file (books.xml) is read into a string variable and then parsed. The result is passed to an anonymous function that formats it before printing it to the console.

When XML elements contain attributes, this version creates an attribute object named $ on the parent and then assigns the values as children of the attribute object. To place attributes as direct children of the parent object (without the intervening $ object), set the mergeAttrs option to true when declaring the parser:

var p = new x2j.Parser( { mergeAttrs: true } );

To learn more, see the documentation for xml2js.

Vital Stats

Lasted tested January 2017: node v7.4.0, npm v4.0.5, xml2js v0.4.17, and MacOS 10.12.3

Revision History

29 Jan 2017: Original post.