Oh Snap!

Please turnoff your ad blocking mode for viewing your site content

Hit enter after type your search item

XML to JavaScript object converter in Node using node-xml2js

/
/
/
73 Views

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 add Custom Fonts in JSPDF | JSPDF Tutorial | Html to Pdf 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  Generate Custom Social Share Buttons With jQuery C Share Plugin

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  Angular 9 Render PDF Documents Using ng2-pdf-viewer Node Module

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 Comment

Your email address will not be published. Required fields are marked *

This div height required for enabling the sticky sidebar
Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views : Ad Clicks : Ad Views :