nodules / xamel

Fast and cozy way to extract data from XML
MIT License
30 stars 5 forks source link

Help converting xamel output to json #18

Closed amitgur closed 10 years ago

amitgur commented 10 years ago

Xamel is really great, I'm using it to preserve xml childes order when loading xml in nodejs/mondodb env. The problem is that mongo db won't exept NodeSet as input to store in the db. right now I'm converting xamel output with this

var jsonObject = JSON.parse(JSON.stringify(result));

And it's working. but I'm looking for a faster, clear solution. any ideas ?

kaero commented 10 years ago

@amitgur Can you explain your task? I think, if you only need is correctly process and store data from XML to mongo, then xamel functionality is excessive for your task. You can use any SAX parser to build plain object and store it to mongo.

You can use xamel.parse source as starting point.

Also, you can fork the xamel, remove all methods from NodeSet and Tag prototypes and use it as xamel-like objects builder.

If you are still interested in NodeSet and Tag methods then you must write some kind of wrapper for serialization and deserialization for the node-sets to the plain objects. Simple xamel tree to plain object serialization can look like this:

var fs = require('fs'),
    util = require('util'),
    xamel = require('xamel'),
    Tag = require('xamel/lib/xml').Tag;

/**
 * @param {NodeSet} nset
 * @returns {Object} plain object
 */
function serializeNodeSet(nset) {
    return nset.reduce(function(res, child) {
        res.push(child instanceof Tag ? {
            name: child.name,
            attrs: child.attrs,
            children: serializeNodeSet(child.children)
        } : child);

        return res;
    }, []);
}

xamel.parse(fs.readFileSync('./test/data/simple.xml', 'utf8'), function(err, xml) {
    var plainObj = serializeNodeSet(xml);

    console.log(util.inspect(plainObj, {depth: 100}));
});

If you fall into too much recursion, then asyncify serializeNodeSet function.

amitgur commented 10 years ago

Thanks for a great answer.After examinig all your options I understand I need to write a spcial SAX parser for my needs.

kaero commented 10 years ago

Great! :)