views:

311

answers:

2

At first glance, I thought using xml data in javascript would be as simple as finding an xml-to-json library and turning my xml into a javascript object tree.

Now, however, I'm realizing that it's possible to create structures in xml that don't map directly to json.

Specifically, this:

<parentNode>
    <fooNode>data1</fooNode>
    <barNode>data2</barNode>
    <fooNode>data3</fooNode>
</parentNode>

The xml-to-json tools I've found convert the previous to something like this:

{
parentnode:{
    foonode:[
        'data1',
        'data3'
    ],
    barnode:'data2'
}

}

in which, the order of the child nodes has been changed. I need to preserve the order of my child nodes. Anyone have any solution that's more elegant than

a) abandoning the idea of automatic conversion and just designing my own javascript object structure and writing code to handle this specific xml schema

or

b) abandoning the idea of any conversion at all, and leaving my xml data as an xml document which I'll then traverse.

+1  A: 

If you need the same element name often and you care about ordering it might be better to stay with XML. What benefits do you expect from using JSON?

Norbert Hartl
Only that it's easier to work with in javascript.
morgancodes
You can change the behaviour of the dom nodes to make your life easier. Or you could wrap it.
Norbert Hartl
+1  A: 

Why not try:

{ parentNode: [
  ["fooNode", "data1"],
  ["barNode", "data2"],
  ["fooNode", "data3"] ]
}

I think it would more or less solve the problem.

And yes, I think you should abandon automatic conversion if it's not flexible enough; instead you might look for an API that makes such mappings trivial.

alamar
This is what I would probably do as well, except I might prefer: `{ parentNode: [ { key: val }, ... ], ... }` rather than 2 element arrays.
thenduks