.gitignore000066400000000000000000000000231516072130100130350ustar00rootroot00000000000000node_modules *.swp README.md000066400000000000000000000012601516072130100123300ustar00rootroot00000000000000# Simple SAX-based XML2JSON Parser. It does not parse the following elements: * CDATA sections * Processing instructions * XML declarations * Entity declarations * Comments ## Installation npm install xml2json ## Usage ```javascript var parser = require('xml2json'); var xml = "bar"; var json = parser.toJson(xml); //returns an string containing the json structure by default console.log(json); ``` * if you want to get the Javascript object then you might want to invoke parser.toJson(xml, {object: true}); * if you want a reversible json to xml then you should use parser.toJson(xml, {reversible: true}); ## License Copyright 2011 BugLabs Inc. All rights reserved. index.js000066400000000000000000000000431516072130100125140ustar00rootroot00000000000000module.exports = require('./lib'); lib/000077500000000000000000000000001516072130100116205ustar00rootroot00000000000000lib/index.js000066400000000000000000000001561516072130100132670ustar00rootroot00000000000000var exports = module.exports; exports.toJson = require('./xml2json'); exports.toXml = require('./json2xml'); lib/json2xml.js000066400000000000000000000022741516072130100137370ustar00rootroot00000000000000var xml = ''; module.exports = function toXml(json) { if (json instanceof Buffer) { json = json.toString(); } var obj = null; if (typeof(json) == 'string') { try { obj = JSON.parse(json); } catch(e) { throw new Error("The JSON structure is invalid"); } } else { obj = json; } var keys = Object.keys(obj); var len = keys.length; for (var i = 0; i < len; i++) { var key = keys[i]; if (Array.isArray(obj[key])) { var elems = obj[key]; var l = elems.length; for (var j = 0; j < l; j++) { xml += '<' + key + '>'; toXml(elems[j]); xml += ''; } } else if (typeof(obj[key]) == 'object') { xml += '<' + key + '>'; toXml(obj[key]); xml += ''; } else if (typeof(obj[key]) == 'string') { if (key == '$t') { xml += obj[key]; } else { xml = xml.replace(/>$/, ''); xml += ' ' + key + "='" + obj[key] + "'>"; } } } return xml; }; lib/xml2json.js000066400000000000000000000047211516072130100137360ustar00rootroot00000000000000var expat = require('node-expat'); var fs = require('fs'); // This object will hold the final result. var obj = currentObject = {}; var ancestors = []; var options = {}; //configuration options function startElement(name, attrs) { if (! (name in currentObject)) { currentObject[name] = attrs; } else if (! (currentObject[name] instanceof Array)) { // Put the existing object in an array. var newArray = [currentObject[name]]; // Add the new object to the array. newArray.push(attrs); // Point to the new array. currentObject[name] = newArray; } else { // An array already exists, push the attributes on to it. currentObject[name].push(attrs); } // Store the current (old) parent. ancestors.push(currentObject); // We are now working with this object, so it becomes the current parent. if (currentObject[name] instanceof Array) { // If it is an array, get the last element of the array. currentObject = currentObject[name][currentObject[name].length - 1]; } else { // Otherwise, use the object itself. currentObject = currentObject[name]; } } function text(data) { data = data.trim(); if (!data.length) { return; } currentObject['$t'] = data; } function endElement(name) { // This should check to make sure that the name we're ending // matches the name we started on. var ancestor = ancestors.pop(); if (!options.reversible) { if ((Object.keys(currentObject).length == 1) && ('$t' in currentObject)) { if (ancestor[name] instanceof Array) { ancestor[name].push(ancestor[name].pop()['$t']); } else { ancestor[name] = currentObject['$t']; } } } currentObject = ancestor; } module.exports = function(xml, _options) { var parser = new expat.Parser('UTF-8'); parser.on('startElement', startElement); parser.on('text', text); parser.on('endElement', endElement); obj = currentObject = {}; ancestors = []; options = { object: false, reversible: false }; for (var opt in _options) { options[opt] = _options[opt]; } if (!parser.parse(xml)) { console.log('-->' + xml + '<--'); throw new Error('There are errors in your xml file: ' + parser.getError()); } if (options.object) { return obj; } return JSON.stringify(obj); }; package.json000066400000000000000000000006571516072130100133500ustar00rootroot00000000000000{ "name" : "xml2json", "version": "0.2.0", "author": "Andrew Turley", "email": "aturley@buglabs.net", "description" : "Converts xml to json using node-expat.", "repository": "git://github.com/buglabs/node-xml2json.git", "main": "index", "maintainers":[ { "name": "Camilo Aguilar", "email": "camilo@buglabs.net"} ], "dependencies": { "node-expat": "1.3.2" } } test/000077500000000000000000000000001516072130100120315ustar00rootroot00000000000000test/fixtures/000077500000000000000000000000001516072130100137025ustar00rootroot00000000000000test/fixtures/domain-reversible.json000066400000000000000000000013411516072130100202030ustar00rootroot00000000000000{"domain":{"type":"qemu","name":{"$t":"QEmu-fedora-i686"},"uuid":{"$t":"c7a5fdbd-cdaf-9455-926a-d65c16db1809"},"memory":{"$t":"219200"},"currentMemory":{"$t":"219200"},"vcpu":{"$t":"2"},"os":{"type":{"arch":"i686","machine":"pc","$t":"hvm"},"boot":{"dev":"cdrom"}},"devices":{"emulator":{"$t":"/usr/bin/qemu-system-x86_64"},"disk":[{"type":"file","device":"cdrom","source":{"file":"/home/user/boot.iso"},"target":{"dev":"hdc"},"readonly":{}},{"type":"file","device":"disk","source":{"file":"/home/user/fedora.img"},"target":{"dev":"hda"}}],"interface":{"type":"network","source":{"network":"default"}},"graphics":{"type":"vnc","port":"-1"}},"ah":[{"type":"rare","foo":"bar","$t":"cosa1"},{"type":"normal","$t":"cosa2"},{"$t":"cosa3"}]}} test/fixtures/domain.json000066400000000000000000000012601516072130100160430ustar00rootroot00000000000000{"domain":{"type":"qemu","name":"QEmu-fedora-i686","uuid":"c7a5fdbd-cdaf-9455-926a-d65c16db1809","memory":"219200","currentMemory":"219200","vcpu":"2","os":{"type":{"arch":"i686","machine":"pc","$t":"hvm"},"boot":{"dev":"cdrom"}},"devices":{"emulator":"/usr/bin/qemu-system-x86_64","disk":[{"type":"file","device":"cdrom","source":{"file":"/home/user/boot.iso"},"target":{"dev":"hdc"},"readonly":{}},{"type":"file","device":"disk","source":{"file":"/home/user/fedora.img"},"target":{"dev":"hda"}}],"interface":{"type":"network","source":{"network":"default"}},"graphics":{"type":"vnc","port":"-1"}},"ah":[{"type":"rare","foo":"bar","$t":"cosa1"},{"type":"normal","$t":"cosa2"},"cosa3"]}} test/fixtures/domain.xml000066400000000000000000000013711516072130100156750ustar00rootroot00000000000000QEmu-fedora-i686c7a5fdbd-cdaf-9455-926a-d65c16db18092192002192002hvm/usr/bin/qemu-system-x86_64cosa1cosa2cosa3 test/test.js000066400000000000000000000034301516072130100133460ustar00rootroot00000000000000var fs = require('fs'); var path = require('path'); var parser = require('../lib'); var assert = require('assert'); var fixturesPath = './fixtures'; fs.readdir(fixturesPath, function(err, files) { for (var i in files) { var file = files[i]; var ext = path.extname(file); if (ext == '.xml') { var basename = path.basename(file, '.xml'); var data = fs.readFileSync(fixturesPath + '/' + file); var result = parser.toJson(data, {reversible: true}); var data2 = fs.readFileSync(fixturesPath + '/' + file); result = parser.toJson(data2); var jsonFile = basename + '.json'; var expected = fs.readFileSync(fixturesPath + '/' + jsonFile) + ''; if (expected) { expected = expected.trim(); } assert.deepEqual(result, expected, jsonFile + ' and ' + file + ' are different'); console.log('[xml2json: ' + file + '->' + jsonFile + '] passed!'); } else if( ext == '.json') { var basename = path.basename(file, '.json'); if (basename.match('reversible')) { var data = fs.readFileSync(fixturesPath + '/' + file); var result = parser.toXml(data); var xmlFile = basename.split('-')[0] + '.xml'; var expected = fs.readFileSync(fixturesPath + '/' + xmlFile) + ''; if (expected) { expected = expected.trim(); } //console.log(result + '<---'); assert.deepEqual(result, expected, xmlFile + ' and ' + file + ' are different'); console.log('[json2xml: ' + file + '->' + xmlFile + '] passed!'); } } } });