How to convert List of Object to XML doc using XStream

NewBeee_Java picture NewBeee_Java · Nov 2, 2010 · Viewed 53k times · Source

How to convert List of Object to XML doc using XStream ?

and how to deserialize it back ?

This is my xml

<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person>  
  <fullname>Guilherme</fullname>
  <age>10</age>
  <address>address,address,address,address,</address>
</person>
<person>  
  <fullname>Guilherme</fullname>
  <age>10</age>
  <address>address,address,address,address,</address>
</person>
</persons>

Person bean contains 3 fields how to convert back it to Bean List using custom converters ?

Answer

dogbane picture dogbane · Nov 2, 2010

You don't necessarily need a CustomConverter.

You need a class to hold your list:

public class PersonList {

    private List<Person> list;

    public PersonList(){
        list = new ArrayList<Person>();
    }

    public void add(Person p){
        list.add(p);
    }
}

To serialise the list to XML:

    XStream xstream = new XStream();
    xstream.alias("person", Person.class);
    xstream.alias("persons", PersonList.class);
    xstream.addImplicitCollection(PersonList.class, "list");

    PersonList list = new PersonList();
    list.add(new Person("ABC",12,"address"));
    list.add(new Person("XYZ",20,"address2"));

    String xml = xstream.toXML(list);

To deserialise xml to a list of person objects:

    String xml = "<persons><person>...</person></persons>";
    PersonList pList = (PersonList)xstream.fromXML(xml);