XML to JavaScript object converter in Node using node-xml2js

XML to JavaScript object converter in Node using node-xml2js

Welcome folks I am back with another blog post. In this post we will be talking about how to convert XML to Javascript Objects easily. So let’s get started with the post.

 

Introduction

 

Simple XML to JavaScript object converter. It supports bi-directional conversion. Uses sax-js and xmlbuilder-js.

READ  PDF Generator in Javascript - JSPDF Tutorial

 

Installation

 

Simplest way to install xml2js is to use npm, just npm install xml2js which will download xml2js and all dependencies.

xml2js is also available via Bower, just bower install xml2js which will download xml2js and all dependencies.

READ  How to make a Simple Keylogger in Javascript - Coding Shiksha

Usage

 

var parseString = require('xml2js').parseString;
var xml = "<root>Hello xml2js!</root>"
parseString(xml, function (err, result) {
    console.dir(result);
});

 

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

var parser = new xml2js.Parser();
fs.readFile(__dirname + '/foo.xml', function(err, data) {
    parser.parseString(data, function (err, result) {
        console.dir(result);
        console.log('Done');
    });
});

 

READ  Generate Custom Social Share Buttons With jQuery C Share Plugin

Promise usage

var xml2js = require('xml2js');
var xml = '<foo></foo>';

// With parser
var parser = new xml2js.Parser(/* options */);
parser.parseStringPromise(data).then(function (result) {
  console.dir(result);
  console.log('Done');
})
.catch(function (err) {
  // Failed
});

// Without parser
xml2js.parseStringPromise(data /*, options */).then(function (result) {
  console.dir(result);
  console.log('Done');
})
.catch(function (err) {
  // Failed
});

 

Leave a Reply

Close Menu