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  How to Design Facebook Login Page in HTML and CSS - Full Source Code

 

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  AJAX JQUERY AND PHP REGISTRATION FORM

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  Login with Google Account using Javascript

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

Indian Desi Tools - Ultimate Tools Website

Demo Description


This will close in 20 seconds