From a5d85fd3d0c551aae801a7419fc27815751a165c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Konstantin=20K=C3=A4fer?= Date: Thu, 3 Feb 2011 13:57:34 -0500 Subject: [PATCH] converts xml mml files to json mml files --- bin/mml2json.js | 64 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100755 bin/mml2json.js diff --git a/bin/mml2json.js b/bin/mml2json.js new file mode 100755 index 0000000..db40716 --- /dev/null +++ b/bin/mml2json.js @@ -0,0 +1,64 @@ +#!/usr/bin/env node + +var xml2js = require('xml2js'), + fs = require('fs'), + sys = require('sys'); + +if (!process.ARGV[2]) { + console.log('Please specify a XML file.'); + process.exit(1); +} + +fs.readFile(process.ARGV[2], 'utf-8', function(err, data) { + if (err) throw err; + + // Replace entities. + var entities = {}; + data.match(/]|"([^"]|\\")*")+>/g).forEach(function(entity) { + var parts = entity.match(/^$/); + entities['&' + parts[1] + ';'] = parts[2]; + }); + data = data.replace(/&\w+;/g, function(entity) { + return entities[entity]; + }); + + function addAttributes(obj) { + if (obj['@']) for (var key in obj['@']) obj[key] = obj['@'][key]; + delete obj['@']; + return obj; + } + + function simplifyExternal(obj) { + if (obj.src) return obj.src; + else return obj; + } + + var parser = new xml2js.Parser(); + parser.addListener('end', function(json) { + console.log(JSON.stringify(json, function(key, value) { + if (!key) { + return addAttributes(value); + } + else if (key === 'Stylesheet') { + if (Array.isArray(value)) return value.map(addAttributes).map(simplifyExternal); + else return [ simplifyExternal(addAttributes(value)) ]; + } + else if (key === 'Layer' || key === 'Stylesheet') { + if (Array.isArray(value)) return value.map(addAttributes); + else return [ addAttributes(value) ]; + } + else if (key === 'Datasource') { + value = addAttributes(value); + value.Parameter.forEach(function(parameter) { + value[parameter['@'].name] = parameter['#']; + }); + delete value.Parameter; + return value; + } + else { + return value; + } + }, 4)); + }); + parser.parseString(data); +}); \ No newline at end of file