3

I want to serialize a list using SimpleXML, so that i can deserialize it again later. I need to preserve the order of elements, or at least achieve the same order everytime i serialize it, so that i can sort it, like, simply reserve the deserialized list.

The order is important because it's a list of GeoPoints that are used to draw a path on a map, and as a path that is actually travelled. Without preserving the order, the path will make no sense at all.

I do not need to use SimpleXML, but i'm already using it for deserializing other stuff, and everything except preserving the order already works, so i would like to avoid the overhead of learning to do this with another serializer. Also, SimpleXML works with Android 2.3.3, which is a must, as this is for an Android app.

I know about the parser and serializer that comes with Android, i actually use the parser, but i didn't do anything with the serializer yet, so it would be quite some overhead again, if there is an easy way of achieving what i need with SimpleXML.

Please note that i am talking about preserving the order of elements in a list, not the elements of a class, for which there is a tag, and which seems to be a quite common problem compared to mine.

Regards

quietmint
  • 13,885
  • 6
  • 48
  • 73

2 Answers2

2

The order is hold (you just need to annotate it with @ElementList) as you can see with the following example:

import java.util.Arrays;
import java.util.List;

import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.core.Persister;

public class SimpleXMLTest {

    public static void main(final String[] args) throws Exception {
        Persister persister = new Persister();

        ModelClass model = new ModelClass(Arrays.asList("Item1", "Item2", "Item3"));

        persister.write(model, System.out);
    }
}

@Root
class ModelClass {

    @ElementList
    private List<String> list;

    public ModelClass() {
    }

    public ModelClass(final List<String> list) {
        super();
        this.list = list;
    }

    public List<String> getList() {
        return list;
    }

}

The output will be:

<modelClass>
   <list class="java.util.Arrays$ArrayList">
      <string>Item1</string>
      <string>Item2</string>
      <string>Item3</string>
   </list>
</modelClass>
Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106
-2

Use the org.simpleframework.xml.Order annotation, here you can specify the order of the elements and attributes.

ng.
  • 7,099
  • 1
  • 38
  • 42