.gitignore 0000664 0000000 0000000 00000000036 14601366532 0013053 0 ustar 00root root 0000000 0000000 node_modules
*.swp
*.DS_Store
.npmignore 0000664 0000000 0000000 00000000015 14601366532 0013057 0 ustar 00root root 0000000 0000000 node_modules
README.md 0000664 0000000 0000000 00000005050 14601366532 0012343 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 a string containing the JSON structure by default
console.log(json);
```
## API
```javascript
parser.toJson(xml, options);
```
```javascript
parser.toXml(json, options);
```
### Options object
```javascript
var options = {
object: false,
reversible: false,
coerce: true,
sanitize: true,
trim: true };
```
* **object:** Returns a Javascript object instead of a JSON string
* **reversible:** Makes the JSON reversible to XML (*)
* **coerce:** Makes type coercion. i.e.: numbers and booleans present in attributes and element values are converted from string to its correspondent data types.
* **trim:** Removes leading and trailing whitespaces as well as line terminators in element values.
* **sanitize:** Sanitizes the following characters:
```javascript
var chars = { '<': '<',
'>': '>',
'(': '(',
')': ')',
'#': '#',
'&': '&',
'"': '"',
"'": ''' };
```
(*) xml2json tranforms CDATA content to JSON, but it doesn't generate a reversible structure.
## License
(The MIT License)
Copyright 2012 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 14601366532 0012526 0 ustar 00root root 0000000 0000000 module.exports = require('./lib');
lib/ 0000775 0000000 0000000 00000000000 14601366532 0011632 5 ustar 00root root 0000000 0000000 lib/index.js 0000664 0000000 0000000 00000000156 14601366532 0013301 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 14601366532 0013744 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 00000012037 14601366532 0013747 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 currentElementName = null;
var options = {}; //configuration options
function startElement(name, attrs) {
currentElementName = name;
if(options.coerce) {
// Looping here in stead of making coerce generic as object walk is unnecessary
Object.keys(attrs).forEach(function(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) {
//console.log('->' + data + '<-');
/*if (!data.trim().length) {
return;
}*/
if (options.trim) {
data = data.trim();
}
if (options.sanitize) {
data = sanitize(data);
}
currentObject['$t'] = coerce((currentObject['$t'] || '') + data);
}
function endElement(name) {
if (currentElementName !== name) {
delete currentObject['$t'];
}
// 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(value) {
if (!options.coerce) {
return value;
}
var num = Number(value);
if (!isNaN(num)) {
return num;
}
var _value = value.toLowerCase();
if (_value == 'true' || _value == 'yes') {
return true;
}
if (_value == 'false' || _value == 'no') {
return false;
}
return value;
}
/**
* Simple sanitization. It is not intended to sanitize
* malicious element values.
*
* character | escaped
* < <
* > >
* ( (
* ) )
* # #
* & &
* " "
* ' '
*/
var chars = { '<': '<',
'>': '>',
'(': '(',
')': ')',
'#': '#',
'&': '&',
'"': '"',
"'": ''' };
function sanitize(value) {
if (typeof value !== 'string') {
return value;
}
Object.keys(chars).forEach(function(key) {
value = value.replace(key, chars[key]);
});
return value;
}
/**
* Parses xml to json using node-expat.
* @param {String|Buffer} xml The xml to be parsed to json.
* @param {Object} _options An object with options provided by the user.
* The available options are:
* - object: If true, the parser returns a Javascript object instead of
* a JSON string.
* - reversible: If true, the parser generates a reversible JSON, mainly
* characterized by the presence of the property $t.
* - sanitize_values: If true, the parser escapes any element value in the xml
* that has any of the following characters: <, >, (, ), #, #, &, ", '.
*
* @return {String|Object} A String or an Object with the JSON representation
* of the XML.
*/
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 = [];
currentElementName = null;
options = {
object: false,
reversible: false,
coerce: true,
sanitize: true,
trim: true
};
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;
}
var json = JSON.stringify(obj);
//See: http://timelessrepo.com/json-isnt-a-javascript-subset
json = json.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
return json;
};
package.json 0000664 0000000 0000000 00000000656 14601366532 0013361 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 <2.0.0"
}
}
test/ 0000775 0000000 0000000 00000000000 14601366532 0012043 5 ustar 00root root 0000000 0000000 test/.gitignore 0000664 0000000 0000000 00000000013 14601366532 0014025 0 ustar 00root root 0000000 0000000 *.DS_Store
test/coerce-overhead.js 0000664 0000000 0000000 00000000767 14601366532 0015446 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 14601366532 0013714 5 ustar 00root root 0000000 0000000 test/fixtures/coerce.json 0000664 0000000 0000000 00000000600 14601366532 0016043 0 ustar 00root root 0000000 0000000 {"itemRecord":{"value":[{"longValue":"12345"},{"stringValue":{"number":"false","$t":"this is a string value"}},{"moneyValue":{"number":"true","currencyId":"USD","$t":"104.95"}},{"moneyValue":{"currencyId":"USD","$t":"104.95"}},{"longValue":"0","bool":{"id":"0","$t":"true"}},{"longValue":"0"},{"dateValue":"2012-02-16T17:03:33.000-07:00"},{"stringValue":"SmDZ8RlMIjDvlEW3KUibzj2Q"}]}} test/fixtures/coerce.xml 0000664 0000000 0000000 00000001167 14601366532 0015703 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