Enatel / xmltojson

Automatically exported from code.google.com/p/x2js
2 stars 0 forks source link

Order of elements #18

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
Hi,
didn't find other way to contact you, so I'm posting my request here.

Let assume an XML:
<root>
    <elementA>first</elementA>
    <elementB>second</elementB>
    <elementA>third</elementA>
    <elementC>fourth</elementC>
    <elementA>fifth</elementA>
    <elementB>sixth</elementB>
</root>

Converting to json we get
- root
  - elementA [array] - first, third, fifth
  - elementB [array] - second, sixth
  - elementC - fourth

Now is there a way to get the original order of elements?

Something like property originalIndex attached to each element?
elementA[0].originalIndex == 0 // first
elementA[1].originalIndex == 2 // third
elementA[2].originalIndex == 4 // fifth
elementB[0].originalIndex == 1 // second
elementB[1].originalIndex == 5 // sixth
elementC.originalIndex == 3    // fourth

Thanks for help.

Original issue reported on code.google.com by martin.p...@gmail.com on 11 Dec 2013 at 1:51

GoogleCodeExporter commented 8 years ago
Hi!
Well, it's a good way to contact me here, why not? :)

The problem you are describing isn't easy to solve without additional 
XSD/knowledge and I can't promise anything right now. I'll think about any 
workaround/solution. 
Thanks!

Original comment by abdulla....@gmail.com on 11 Dec 2013 at 5:37

GoogleCodeExporter commented 8 years ago
Nice library unfortuantly the element order is quite a big one for me as well. 
One idea I have for fixing this is to simply put a wrapper on elements that 
contains their tag name. Currently given this xml input

<root>
  <tag1 hello="world" />
  <tag2 />
  <tag1 />
</root>

you get this json

{
   "root":{
      "tag1":[
         {
            "_hello":"world"
         },
         ""
      ],
      "tag2":""
   }
}

As you can see no order. Now imagine if the json returned was this

[
   {
      "namespace": "",
      "localName": "root"
      "children": [
         {
            "namespace": "",
            "localName": "tag1",
            "children": [],
            "attributes": {
               "hello": "world"
            }
         },
         {
            "namespace": "",
            "localName": "tag2",
            "children": [],
            "attributes": {}
         },
         {
            "namespace": "",
            "localName": "tag1",
            "children": [],
            "attributes": {}
         },
      ]
   }
]

This output is much more verbose but it has its benefits, for 1 order is 
preserved and additional information can be added without conflicting with 
attribute names. Because this changes the whole structure of the response a 
change like this would have to a v2 change.

Original comment by ned.stua...@gmail.com on 23 Jun 2014 at 10:30