Skip to content

Instantly share code, notes, and snippets.

@MrTrick
Last active October 30, 2015 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MrTrick/e946529e13843ec49709 to your computer and use it in GitHub Desktop.
Save MrTrick/e946529e13843ec49709 to your computer and use it in GitHub Desktop.
//package.json: {"dependencies": {"xml2js": "~0.4.13","underscore": "~1.8.3"}}
var xml2js = require('xml2js');
var fs = require('fs');
var _ = require('underscore');
_.isScalar = function(o) { return o===null || (typeof o !== "object"); };
function summarizeXMLObject(obj, context) {
//Assume that array elements all have the same internals
if (_.isArray(obj)) {
//console.log(context);
summarizeXMLObject(obj[0], context+"[]");
}
//Enumerate and recurse into most objects
else if (_.isObject(obj)) {
_.each(obj, function(v,k) {
//Is this a '$' node? It's an attribute holder - subattrs are all leaves
if (k==='$') {
_.each(v, function(v,k) { console.log(context+"("+k+")\t", v ); });
//Is this a leaf node? Show the value.
} else if (_.isScalar(v)) {
console.log(context+"/"+k+"\t", v);
//Otherwise it has descendents, show them
} else {
context = context ? context+"/"+k : k;
console.log(context);
summarizeXMLObject(v, context);
}
});
}
}
var filename = process.argv[2];
if (typeof filename === "undefined") throw "Pass input filename as first arg";
if (!fs.existsSync(filename)) throw "Input filename does not exist";
var parser = new xml2js.Parser({explicitArray : false});
fs.readFile(filename, function(err, data) {
parser.parseString(data, function (err, result) {
console.log("NODE", "EXAMPLE CONTENT");
summarizeXMLObject(result, "");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment