Skip to content
This repository was archived by the owner on Jan 7, 2021. It is now read-only.

Commit 8a4718e

Browse files
committed
Fixes #69 by applying lazy sanitization and coercion.
Expat tokenizes text elements and calls our text callback per each token causing the behavior explained in #69. This commit does sanitization and coercion once we stop receiving text tokens from a given XML element.
1 parent 1af71b6 commit 8a4718e

4 files changed

Lines changed: 17 additions & 18 deletions

File tree

lib/json2xml.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
var sanitizer = require('./sanitize.js')
22

3-
module.exports = function toXml(json, options) {
3+
module.exports = function (json, options) {
44
if (json instanceof Buffer) {
55
json = json.toString();
66
}

lib/xml2json.js

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -49,23 +49,22 @@ function startElement(name, attrs) {
4949
}
5050

5151
function text(data) {
52-
//console.log('->' + data + '<-');
53-
/*if (!data.trim().length) {
54-
return;
55-
}*/
52+
currentObject['$t'] = (currentObject['$t'] || '') + data;
53+
}
5654

57-
if (options.trim) {
58-
data = data.trim();
59-
}
55+
function endElement(name) {
56+
if (currentObject['$t']) {
57+
if (options.trim) {
58+
currentObject['$t'] = currentObject['$t'].trim()
59+
}
6060

61-
if (options.sanitize) {
62-
data = sanitizer.sanitize(data);
63-
}
61+
if (options.sanitize) {
62+
currentObject['$t'] = sanitizer.sanitize(currentObject['$t']);
63+
}
6464

65-
currentObject['$t'] = coerce((currentObject['$t'] || '') + data);
66-
}
65+
currentObject['$t'] = coerce(currentObject['$t']);
66+
}
6767

68-
function endElement(name) {
6968
if (currentElementName !== name) {
7069
delete currentObject['$t'];
7170
}

test/fixtures/large.json

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.

test/test.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,9 @@ fs.readdir(fixturesPath, function(err, files) {
3737
if (expected) {
3838
expected = expected.trim();
3939
}
40-
/*console.log(result);
41-
console.log('============ Expected ===============');
42-
console.log(expected)*/
40+
// console.log(result);
41+
// console.log('============ Expected ===============');
42+
// console.log(expected)
4343
assert.deepEqual(result, expected, jsonFile + ' and ' + file + ' are different');
4444
console.log('[xml2json: ' + file + '->' + jsonFile + '] passed!');
4545
} else if( ext == '.json') {

0 commit comments

Comments
 (0)