.gitignore 0000664 0000000 0000000 00000000023 15160746067 0013055 0 ustar 00root root 0000000 0000000 node_modules
*.swp
.npmignore 0000664 0000000 0000000 00000000015 15160746067 0013065 0 ustar 00root root 0000000 0000000 node_modules
README.md 0000664 0000000 0000000 00000003300 15160746067 0012345 0 ustar 00root root 0000000 0000000 # 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
(The MIT License)
Copyright 2011 BugLabs. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE. index.js 0000664 0000000 0000000 00000000043 15160746067 0012534 0 ustar 00root root 0000000 0000000 module.exports = require('./lib');
lib/ 0000775 0000000 0000000 00000000000 15160746067 0011640 5 ustar 00root root 0000000 0000000 lib/index.js 0000664 0000000 0000000 00000000156 15160746067 0013307 0 ustar 00root root 0000000 0000000 var exports = module.exports;
exports.toJson = require('./xml2json');
exports.toXml = require('./json2xml');
lib/json2xml.js 0000664 0000000 0000000 00000002611 15160746067 0013752 0 ustar 00root root 0000000 0000000 module.exports = function toXml(json, xml) {
var xml = xml || '';
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;
// First pass, extract strings only
for (var i = 0; i < len; i++) {
var key = keys[i];
if (typeof(obj[key]) == 'string') {
if (key == '$t') {
xml += obj[key];
} else {
xml = xml.replace(/>$/, '');
xml += ' ' + key + "='" + obj[key] + "'>";
}
}
}
// Second path, now handle sub-objects and arrays
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 + '>';
xml = toXml(elems[j], xml);
xml += '' + key + '>';
}
} else if (typeof(obj[key]) == 'object') {
xml += '<' + key + '>';
xml = toXml(obj[key], xml);
xml += '' + key + '>';
}
}
return xml;
};
lib/xml2json.js 0000664 0000000 0000000 00000006111 15160746067 0013751 0 ustar 00root root 0000000 0000000 var expat = require('node-expat');
var fs = require('fs');
// This object will hold the final result.
var obj = {};
var currentObject = {};
var ancestors = [];
var options = {}; //configuration options
function startElement(name, attrs) {
if(options.coerce) {
// Looping here in stead of making coerce generic as object walk is unnecessary
for (var key in attrs) {
if (attrs.hasOwnProperty(key)) {
attrs[key] = coerce(attrs[key]);
}
}
}
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'] = coerce((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;
}
function coerce(val) {
if (!options.coerce) {
return val;
}
var num = Number(val);
if (!isNaN(num)) {
return num;
}
switch (val.toLowerCase()){
case 'true':
case 'yes':
return true;
case 'false':
case 'no':
return false;
default: return val;
}
}
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)) {
throw new Error('There are errors in your xml file: ' + parser.getError());
}
if (options.object) {
return obj;
}
return JSON.stringify(obj);
};
package.json 0000664 0000000 0000000 00000000645 15160746067 0013365 0 ustar 00root root 0000000 0000000 { "name" : "xml2json",
"version": "0.2.4",
"author": "Andrew Turley",
"email": "aturley@buglabs.net",
"description" : "Converts xml to json and viceverza, using node-expat.",
"repository": "git://github.com/buglabs/node-xml2json.git",
"main": "index",
"contributors":[ {"name": "Camilo Aguilar", "email": "camilo@buglabs.net"}],
"dependencies": {
"node-expat": "1.4.1"
}
}
test/ 0000775 0000000 0000000 00000000000 15160746067 0012051 5 ustar 00root root 0000000 0000000 test/coerce-overhead.js 0000664 0000000 0000000 00000000767 15160746067 0015454 0 ustar 00root root 0000000 0000000 var fs = require('fs');
var parser = require('../lib');
var file = __dirname + '/fixtures/large.xml';
var data = fs.readFileSync(file);
// With coercion
var t0 = Date.now();
for(var i = 0; i < 10000; i++) {
var result = parser.toJson(data, {reversible: true, coerce: true, object: true});
}
console.log(Date.now() - t0);
// Without coercion
var t0 = Date.now();
for(var i = 0; i < 10000; i++) {
result = parser.toJson(data, {reversible: true, object: true});
}
console.log(Date.now() - t0);
test/fixtures/ 0000775 0000000 0000000 00000000000 15160746067 0013722 5 ustar 00root root 0000000 0000000 test/fixtures/coerce.xml 0000664 0000000 0000000 00000001167 15160746067 0015711 0 ustar 00root root 0000000 0000000
12345
this is a string value
104.95
104.95
0
true
0
2012-02-16T17:03:33.000-07:00
SmDZ8RlMIjDvlEW3KUibzj2Q