Last active
February 6, 2018 23:38
-
-
Save fmarcia/fbb6d1d5e15b9f28fcc6ddf80a271c72 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!env node | |
const fs = require("fs"); | |
const sax = require("./sax"); | |
function parseXml(filename) { | |
const parser = sax.parser(true); | |
const doc = {}; | |
let current = doc; | |
function string(type, text) { | |
text = text.replace(/(^\s+|\s+$)/g, ""); | |
if (text) { | |
const rank = current[`#${type}_rank`]; | |
current[`#${type}_${rank}`] = text; | |
current[`#${type}_rank`] += 1; | |
} | |
} | |
parser.ontext = string.bind(null, "text"); | |
parser.oncomment = string.bind(null, "comment"); | |
parser.onopencdata = function () { | |
current[`#cdata_${current["#cdata_rank"]}`] = ""; | |
}; | |
parser.oncdata = function (cdata) { | |
current[`#cdata_${current["#cdata_rank"]}`] += cdata; | |
}; | |
parser.onclosecdata = function () { | |
current["#cdata_rank"] += 1; | |
}; | |
parser.onerror = function (error) { | |
console.error(error.toString()); | |
parser.close(); | |
}; | |
parser.onopentag = function (node) { | |
const newChild = { | |
"#parent": current, | |
"#text_rank": 0, | |
"#comment_rank": 0, | |
"#cdata_rank": 0 | |
}; | |
for (let a in node.attributes) { | |
if (node.attributes.hasOwnProperty(a)) { | |
newChild[`-${a}`] = node.attributes[a]; | |
} | |
} | |
if (current[node.name]) { | |
if (current[node.name].constructor === Object) { | |
current[node.name] = [ current[node.name] ]; | |
} | |
current[node.name].push(newChild); | |
if (!node.isSelfClosing) { | |
current = newChild; | |
} | |
} else { | |
current[node.name] = newChild; | |
} | |
current = newChild; | |
}; | |
parser.onclosetag = function (name) { | |
let target; | |
current = current["#parent"]; | |
if (current[name].constructor === Array) { | |
target = current[name][current[name].length - 1]; | |
} else { | |
target = current[name]; | |
} | |
delete target["#parent"]; | |
delete target["#text_rank"]; | |
delete target["#comment_rank"]; | |
delete target["#cdata_rank"]; | |
}; | |
parser.write(fs.readFileSync(filename).toString()).close(); | |
return doc; | |
} | |
console.log(JSON.stringify(parseXml(process.argv[2]), 0, " ")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment