.editorconfig 0000664 0000000 0000000 00000000637 14601465134 0013545 0 ustar 00root root 0000000 0000000 # EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org
root = true
[*]
# Change these settings to your own preference
indent_style = space
indent_size = 4
# We recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
.github/ 0000775 0000000 0000000 00000000000 14601465134 0012422 5 ustar 00root root 0000000 0000000 .github/workflows/ 0000775 0000000 0000000 00000000000 14601465134 0014457 5 ustar 00root root 0000000 0000000 .github/workflows/build.yml 0000664 0000000 0000000 00000001705 14601465134 0016304 0 ustar 00root root 0000000 0000000 # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
name: build
on:
schedule:
- cron: '0 0 1 * *'
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: ['lts/*']
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- run: npm i -g grunt-cli
- run: npm install
- run: npm run test
.gitignore 0000664 0000000 0000000 00000000044 14601465134 0013050 0 ustar 00root root 0000000 0000000 node_modules
*.swp
*.DS_Store
build
.npmignore 0000664 0000000 0000000 00000000043 14601465134 0013056 0 ustar 00root root 0000000 0000000 node_modules
test
./build
/.github
.travis.yml 0000664 0000000 0000000 00000001674 14601465134 0013203 0 ustar 00root root 0000000 0000000 sudo: required
language: node_js
cache:
npm: false
node_js:
- lts/*
before_script:
- npm install -g grunt-cli npm
env:
matrix:
- CXX="g++-4.8"
global:
secure: EW8wQ4ZTe859edhfgDplSKP/VLBLOkuU4uDiIY9sP4Wg/b+T0B4py9DPOZQUXhx6iBg87gZAHZMPGiJCj+4fWsQYlImAfgSZ6kq9O7a/dsIp8zWQD4IFc8TVDYW262AesUPjDMH+U7ynzH11PkCHVgjT8dioWCtDYf7sjn7Iyo//4xC4PF4OhHmsjsE53OBdnNknqT3z5LIc5s3UypGdLM6QSgz1a7XEgjmcOsx8+Z6ZWeIwRBHleJ/th95B5rTbb2AC5U4Q8FxX15EsLlc8NRn02wi7EVg45gEdl5KmdTWI3ZEdkvEJVAyu5Nm72ouGNiwSeDpcKc7ciRDCw6kGFLvdw6BbjPtlzCTFXX2P4JQc/RY+asA/95CjsIxjVQHUZhS8yWDUwyd46h3mI74OmXY/p48ueDPvK3ZBI2GC1WOg3A7L1grfcWC8nQjaCd8Ry+7RVXb4hI5b9+v27SuS+e9cTfDcyIg37wBPblP08MCVFvTstdwzMtl6CbHe/IpFIBirfg/zVa6nlp7XoRToBA72hVL8HqNGmf4XAt/UKTvaS/feUHJqrRDolXu1xzr9yWzoHC75mPVqfx+R571UB5UNIUZGKNM7z1jELodYWy9xw1EgD6qNwiI2/QNxxkz2xeHRYXRjBtb83eJMI5IrdB6lxB9IvZsXCPa8K94codA=
addons:
apt:
sources:
- ubuntu-toolchain-r-test
packages:
- g++-4.8
- gcc-4.8
AUTHORS 0000664 0000000 0000000 00000001366 14601465134 0012140 0 ustar 00root root 0000000 0000000 Arek W arek01@gmail.com
Camilo Aguilar camilo.aguilar@gmail.com
Craig Condon craig@spiceapps.com
Daniel Bretoi daniel@bretoi.com
Daniel Juhl danieljuhl@gmail.com
Dmitry Fink github@finik.net
Garvit Sharma garvits45@gmail.com
Julian Duque julianduquej@gmail.com
Karl Böhlmark karl.bohlmark@edgeware.tv
Kevin McTigue firefoxman1@gmail.com
Kirill Vergun github.com@o-nix.me
Maher Beg maherbeg@gmail.com
Nicholas Kinsey pyrotechnick@feistystudios.com
Rob Brackett rob@robbrackett.com
Subbu Allamaraju subbu@ebaysf.com
The Gitter Badger badger@gitter.im
Trotter Cashion cashion@gmail.com
Yan idy0013@gmail.com
Ziggy Jonsson ziggy.jonsson.nyc@gmail.com
andres suarez zertosh@gmail.com
andris9 andris@node.ee
fengmk2 fengmk2@gmail.com
patrikx3 alabard@gmail.com
Gruntfile.js 0000664 0000000 0000000 00000000454 14601465134 0013362 0 ustar 00root root 0000000 0000000 module.exports = (grunt) => {
const builder = require(`corifeus-builder`);
const loader = new builder.loader(grunt);
loader.js({
replacer: {
type: 'p3x',
npmio: true,
},
});
grunt.registerTask('default', builder.config.task.build.js);
}; LICENSE 0000664 0000000 0000000 00000002322 14601465134 0012066 0 ustar 00root root 0000000 0000000
@license p3x-xml2json v2021.10.153
Converts xml to json and vice-versa, using node-expat
https://corifeus.com/xml2json
Copyright (c) 2021 Patrik Laszlo / P3X / Corifeus and contributors.
MIT License
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.
LICENSE.old 0000664 0000000 0000000 00000002067 14601465134 0012651 0 ustar 00root root 0000000 0000000 (The MIT License)
Copyright (c) 2016 xml2json AUTHORS
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.
README.md 0000664 0000000 0000000 00000013310 14601465134 0012337 0 ustar 00root root 0000000 0000000 [//]: #@corifeus-header
[![NPM](https://nodei.co/npm/p3x-xml2json.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/p3x-xml2json/)
[![Donate for Corifeus / P3X](https://img.shields.io/badge/Donate-Corifeus-003087.svg)](https://paypal.me/patrikx3) [![Contact Corifeus / P3X](https://img.shields.io/badge/Contact-P3X-ff9900.svg)](https://www.patrikx3.com/en/front/contact) [![Corifeus @ Facebook](https://img.shields.io/badge/Facebook-Corifeus-3b5998.svg)](https://www.facebook.com/corifeus.software) [![Build Status](https://github.com/patrikx3/xml2json/workflows/build/badge.svg)](https://github.com/patrikx3/xml2json/actions?query=workflow%3Abuild)
[![Uptime Robot ratio (30 days)](https://img.shields.io/uptimerobot/ratio/m780749701-41bcade28c1ea8154eda7cca.svg)](https://stats.uptimerobot.com/9ggnzcWrw)
# Converts xml to json and vice-versa, using node-expat v2021.10.153
# Warning
2021. November 17.
All patrikx3.com, corifeus.com and sub-domains are offline. Will come back again on 2021. November 18.
**Bugs are evident™ - MATRIX️**
### NodeJS LTS is supported
### Built on NodeJs version
```txt
v16.13.0
```
# Description
[//]: #@corifeus-header:end
## Simple XML2JSON Parser
### The info about the fork
The https://github.com/buglabs/node-xml2json/pull/180 maintainers (`buglabs`, no e-mail, no GitHub) are not responsive. So, I created a small fix, that works perfectly, it is named as `p3x-xml2json`. It is the same as the original, just works with NodeJs 12.
I am open to merge pull requests. I maintain. Please free, to contact me.
Besides, I have upgraded all packages to the latest versions.
## Verbose description
It does not parse the following elements:
* CDATA sections (*)
* Processing instructions
* XML declarations
* Entity declarations
* Comments
This module uses node-expat which will require extra steps if you want to get it installed on Windows. Please
refer to its [documentation](https://github.com/astro/node-expat/blob/master/README.md#windows).
## Installation
```bash
$ npm install p3x-xml2json
```
## Usage
```javascript
var parser = require('p3x-xml2json');
var xml = "bar";
console.log("input -> %s", xml)
// xml to json
var json = parser.toJson(xml);
console.log("to json -> %s", json);
// json to xml
var xml = parser.toXml(json);
console.log("back to xml -> %s", xml)
```
## API
```javascript
parser.toJson(xml, options);
```
```javascript
parser.toXml(json);
```
### Options object for `toJson`
Default values:
```javascript
var options = {
object: false,
reversible: false,
coerce: false,
sanitize: true,
trim: true,
arrayNotation: false
alternateTextNode: false
};
```
* **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. Coerce can be optionally defined as an object with specific methods of coercion based on attribute name or tag name, with fallback to default coercion.
* **trim:** Removes leading and trailing whitespaces as well as line terminators in element values.
* **arrayNotation:** XML child nodes are always treated as arrays NB: you can specify a selective array of nodes for this to apply to instead of the whole document.
* **sanitize:** Sanitizes the following characters present in element values:
```javascript
var chars = {
'<': '<',
'>': '>',
'(': '(',
')': ')',
'#': '#',
'&': '&',
'"': '"',
"'": '''
};
```
* **alternateTextNode:** Changes the default textNode property from $t to _t when option is set to true. Alternatively a string can be specified which will override $t to what ever the string is.
### Options object for `toXml`
Default values:
```javascript
var options = {
sanitize: false,
ignoreNull: false
};
```
* `sanitize: false` is the default option to behave like previous versions
* **ignoreNull:** Ignores all null values
(*) xml2json tranforms CDATA content to JSON, but it doesn't generate a reversible structure.
[//]: #@corifeus-footer
---
🙏 This is an open-source project. Star this repository, if you like it, or even donate to maintain the servers and the development. Thank you so much!
Possible, this server, rarely, is down, please, hang on for 15-30 minutes and the server will be back up.
All my domains ([patrikx3.com](https://patrikx3.com) and [corifeus.com](https://corifeus.com)) could have minor errors, since I am developing in my free time. However, it is usually stable.
**Note about versioning:** Versions are cut in Major.Minor.Patch schema. Major is always the current year. Minor is either 4 (January - June) or 10 (July - December). Patch is incremental by every build. If there is a breaking change, it should be noted in the readme.
---
[**P3X-XML2JSON**](https://corifeus.com/xml2json) Build v2021.10.153
[![Donate for Corifeus / P3X](https://img.shields.io/badge/Donate-Corifeus-003087.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=QZVM4V6HVZJW6) [![Contact Corifeus / P3X](https://img.shields.io/badge/Contact-P3X-ff9900.svg)](https://www.patrikx3.com/en/front/contact) [![Like Corifeus @ Facebook](https://img.shields.io/badge/LIKE-Corifeus-3b5998.svg)](https://www.facebook.com/corifeus.software)
## P3X Sponsor
[IntelliJ - The most intelligent Java IDE](https://www.jetbrains.com/?from=patrikx3)
[![JetBrains](https://cdn.corifeus.com/assets/svg/jetbrains-logo.svg)](https://www.jetbrains.com/?from=patrikx3)
[//]: #@corifeus-footer:end
bin/ 0000775 0000000 0000000 00000000000 14601465134 0011632 5 ustar 00root root 0000000 0000000 bin/xml2json 0000775 0000000 0000000 00000000667 14601465134 0013345 0 ustar 00root root 0000000 0000000 #!/usr/bin/env node
var xml2json = require('../');
var pkg = require('../package.json');
var xml = '';
var args = process.argv.slice(2)
var arg = args[0]
if (arg == '--version') {
console.log(pkg.version)
process.exit(0)
}
process.stdin.on('data', function (data) {
xml += data;
});
process.stdin.resume();
process.stdin.on('end', function () {
json = xml2json.toJson(xml)
process.stdout.write(json + '\n')
});
example.js 0000664 0000000 0000000 00000000404 14601465134 0013051 0 ustar 00root root 0000000 0000000 var parser = require('./index');
// xml to json
var xml = "bar";
console.log("input -> %s", xml)
var json = parser.toJson(xml);
console.log("to json -> %s", json);
var xml = parser.toXml(json);
console.log("back to xml -> %s", xml)
index.js 0000664 0000000 0000000 00000000043 14601465134 0012524 0 ustar 00root root 0000000 0000000 module.exports = require('./src');
package.json 0000664 0000000 0000000 00000002037 14601465134 0013352 0 ustar 00root root 0000000 0000000 {
"name": "p3x-xml2json",
"corifeus": {
"prefix": "p3x-",
"publish": true,
"type": "p3x",
"code": "Done",
"nodejs": "v16.13.0",
"opencollective": false,
"reponame": "xml2json",
"build": true
},
"version": "2021.10.153",
"description": "Converts xml to json and vice-versa, using node-expat",
"repository": {
"type": "git",
"url": "git+https://github.com/patrikx3/xml2json.git"
},
"license": "MIT",
"main": "index",
"scripts": {
"test": "grunt && lab -I globalThis --a @hapi/code -v -t 93 test/test.js"
},
"dependencies": {
"@hapi/hoek": "^9.2.1",
"joi": "^17.4.2",
"node-expat": "^2.4.0"
},
"bin": {
"p3x-xml2json": "bin/xml2json"
},
"devDependencies": {
"@hapi/code": "^8.0.4",
"@hapi/lab": "^24.4.0",
"corifeus-builder": "^2021.10.181"
},
"engines": {
"node": ">=12.13.0"
},
"homepage": "https://corifeus.com/xml2json"
} src/ 0000775 0000000 0000000 00000000000 14601465134 0011651 5 ustar 00root root 0000000 0000000 src/index.js 0000664 0000000 0000000 00000000156 14601465134 0013320 0 ustar 00root root 0000000 0000000 var exports = module.exports;
exports.toJson = require('./xml2json');
exports.toXml = require('./json2xml');
src/json2xml.js 0000664 0000000 0000000 00000005767 14601465134 0014002 0 ustar 00root root 0000000 0000000 var sanitizer = require('./sanitize.js')
module.exports = function (json, options) {
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 toXml = new ToXml(options);
toXml.parse(obj);
return toXml.xml;
}
ToXml.prototype.parse = function (obj) {
if (!obj) return;
var self = this;
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], value = obj[key], isArray = Array.isArray(value);
var type = typeof (value);
if (type == 'string' || type == 'number' || type == 'boolean' || isArray) {
var it = isArray ? value : [value];
it.forEach(function (subVal) {
if (typeof (subVal) != 'object') {
if (key == '$t') {
self.addTextContent(subVal);
} else {
self.addAttr(key, subVal);
}
}
});
}
}
// 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++) {
var elem = elems[j];
if (typeof (elem) == 'object') {
self.openTag(key);
self.parse(elem);
self.closeTag(key);
}
}
} else if (typeof (obj[key]) == 'object' && !(self.options.ignoreNull && obj[key] === null)) {
self.openTag(key);
self.parse(obj[key]);
self.closeTag(key);
}
}
};
ToXml.prototype.openTag = function (key) {
this.completeTag();
this.xml += '<' + key;
this.tagIncomplete = true;
}
ToXml.prototype.addAttr = function (key, val) {
if (this.options.sanitize) {
val = sanitizer.sanitize(val, false, true);
}
this.xml += ' ' + key + '="' + val + '"';
}
ToXml.prototype.addTextContent = function (text) {
this.completeTag();
var newText = (this.options.sanitize ? sanitizer.sanitize(text) : text);
this.xml += newText;
}
ToXml.prototype.closeTag = function (key) {
this.completeTag();
this.xml += '' + key + '>';
}
ToXml.prototype.completeTag = function () {
if (this.tagIncomplete) {
this.xml += '>';
this.tagIncomplete = false;
}
}
function ToXml(options) {
var defaultOpts = {
sanitize: false,
ignoreNull: false
};
if (options) {
for (var opt in options) {
defaultOpts[opt] = options[opt];
}
}
this.options = defaultOpts;
this.xml = '';
this.tagIncomplete = false;
}
src/sanitize.js 0000664 0000000 0000000 00000002341 14601465134 0014035 0 ustar 00root root 0000000 0000000 /**
* Simple sanitization. It is not intended to sanitize
* malicious element values.
*
* character | escaped
* < <
* > >
* ( (
* ) )
* # #
* & &
* " "
* ' '
*/
// used for body text
var charsEscape = {
'&': '&',
'<': '<',
'>': '>'
};
var charsUnescape = {
'&': '&',
'#': '#',
'<': '<',
'>': '>',
'(': '(',
')': ')',
'"': '"',
''': "'",
"": "\u001F"
};
// used in attribute values
var charsAttrEscape = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
function escapeRegExp(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
// sanitize body text
exports.sanitize = function sanitize(value, reverse, attribute) {
if (typeof value !== 'string') {
return value;
}
var chars = reverse ? charsUnescape : (attribute ? charsAttrEscape : charsEscape);
var keys = Object.keys(chars);
keys.forEach(function (key) {
value = value.replace(new RegExp(escapeRegExp(key), 'g'), chars[key]);
});
return value;
};
src/xml2json.js 0000664 0000000 0000000 00000013726 14601465134 0013774 0 ustar 00root root 0000000 0000000 var expat = require('node-expat');
var sanitizer = require('./sanitize.js')
var joi = require('joi');
var hoek = require('@hapi/hoek');
// 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
for (var key in attrs) {
attrs[key] = coerce(attrs[key], key);
}
}
if (!(name in currentObject)) {
if (options.arrayNotation || options.forceArrays[name]) {
currentObject[name] = [attrs];
} else {
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) {
currentObject[textNodeName()] = (currentObject[textNodeName()] || '') + data;
}
function endElement(name) {
if (currentObject[textNodeName()]) {
if (options.trim) {
currentObject[textNodeName()] = currentObject[textNodeName()].trim()
}
// node-expat already reverse sanitizes it whether we like it or not
//if (options.sanitize) {
// currentObject[textNodeName()] = sanitizer.sanitize(currentObject[textNodeName()], true);
//}
currentObject[textNodeName()] = coerce(currentObject[textNodeName()], name);
}
if (currentElementName !== name) {
delete currentObject[textNodeName()];
}
// 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 ((textNodeName() in currentObject) && (Object.keys(currentObject).length == 1)) {
if (ancestor[name] instanceof Array) {
ancestor[name].push(ancestor[name].pop()[textNodeName()]);
} else {
ancestor[name] = currentObject[textNodeName()];
}
}
}
currentObject = ancestor;
}
function coerce(value, key) {
if (!options.coerce || value.trim() === '') {
return value;
}
if (typeof options.coerce[key] === 'function')
return options.coerce[key](value);
var num = Number(value);
if (!isNaN(num)) {
return num;
}
var _value = value.toLowerCase();
if (_value == 'true') {
return true;
}
if (_value == 'false') {
return false;
}
return value;
}
function textNodeName() {
return options.alternateTextNode ? typeof options.alternateTextNode === 'string' ? options.alternateTextNode : '_t' : '$t'
}
/**
* 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: <, >, (, ), #, #, &, ", '.
* - alternateTextNode (boolean OR string):
* If false or not specified: default of $t is used
* If true, whenever $t is returned as an end point, is is substituted with _t
* it String, whenever $t is returned as an end point, is is substituted with the String value (care advised)
*
* @return {String|Object} A String or an Object with the JSON representation
* of the XML.
*/
module.exports = function (xml, _options) {
_options = _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;
var schema = joi.object( {
object: joi.boolean().default(false),
reversible: joi.boolean().default(false),
coerce: joi.alternatives([joi.boolean(), joi.object()]).default(false),
sanitize: joi.boolean().default(true),
trim: joi.boolean().default(true),
arrayNotation: joi.alternatives([joi.boolean(), joi.array()]).default(false),
alternateTextNode: [joi.boolean().default(false), joi.string().default(false)]
});
var validation = schema.validate(_options);
hoek.assert(validation.error === undefined, validation.error);
options = validation.value;
options.forceArrays = {};
if (Array.isArray(options.arrayNotation)) {
options.arrayNotation.forEach(function (i) {
options.forceArrays[i] = true;
});
options.arrayNotation = false;
}
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;
};
test/ 0000775 0000000 0000000 00000000000 14601465134 0012041 5 ustar 00root root 0000000 0000000 test/.gitignore 0000664 0000000 0000000 00000000013 14601465134 0014023 0 ustar 00root root 0000000 0000000 *.DS_Store
test/coerce-overhead.js 0000664 0000000 0000000 00000000767 14601465134 0015444 0 ustar 00root root 0000000 0000000 var fs = require('fs');
var parser = require('../src');
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 14601465134 0013712 5 ustar 00root root 0000000 0000000 test/fixtures/alternate-text-node-A.json 0000664 0000000 0000000 00000000153 14601465134 0020646 0 ustar 00root root 0000000 0000000 {"unit":{"test":{"case":[{"justText":{"$t":"blah blah"}},{"attribText":{"attrib":"das","$t":"capital"}}]}}} test/fixtures/alternate-text-node-A.xml 0000664 0000000 0000000 00000000257 14601465134 0020502 0 ustar 00root root 0000000 0000000
blah blah
capital