Convert XML to JSON

Shows one way to use Node.js to convert XML to JSON

The xml2js module provides a convenient way to convert XML to JSON using Node.js:

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 xml2js docs.

Vital statistics

  • 15 Feb 2024: Migrated to new site and style
  • Lasted tested January 2017:
    • Node: v7.4.0
    • npm v4.05
    • xml2js v0.4.17
    • MacOS 10.12.3
  • 29 Jan 2017: First post