Converting complex js objects to xml

The xml node package offers “fast and simple Javascript-based XML generation”.

I had hoped that it would be as simple as:

var xml = require('xml');

var result = xml({
    FOO: {
        BAR: "something"
    }
});

But that only included the top level element:

<FOO />

After some RTFM, and a few false starts, it became clear that you need to represent each child node as an array of key value pairs:

xml({
    FOO: [
        {_attrs: { abra: "cadabra" },
        { BAR: "something" },
        { BAZ: "else" }
    ]
});

Which should result in XML like this:

<FOO abra="cadabra">
    <BAR>something</BAR>
    <BAZ>else</BAZ>
</FOO>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s