toJson = 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 = { 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 = joi.validate(_options, schema); hoek.assert(validation.error === null, 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; }
...
var parser = require('./index');
// xml to json
var xml = "<foo attr=\"value\">bar</foo>";
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)
...
toXml = 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; }
...
// xml to json
var xml = "<foo attr=\"value\">bar</foo>";
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)
...
function sanitize(value, reverse) { if (typeof value !== 'string') { return value; } Object.keys(chars).forEach(function(key) { if (reverse) { value = value.replace(new RegExp(escapeRegExp(chars[key]), 'g'), key); } else { value = value.replace(new RegExp(escapeRegExp(key), 'g'), chars[key]); } }); return value; }
...
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)
}
this.xml += ' ' + key + '="' + val + '"';
}
ToXml.prototype.addTextContent = function(text) {
this.completeTag();
this.xml += text;
}
...