Convert xml to arraylist using xstream

We showed how to transform xml to java hashmap with xstream in this example will show how to convert xml to a java arraylist and arraylist to xml using xstream. XStream is a java library to convert Java Objects into XML and then back again. The set up will create a POJO Funeral object, an arraylist funerals and initialize the arraylist with some set up data.

Setup

class Funeral {

        Date date;
        String funeralHome;
        String person;
}

private List<Funeral> funerals;

@Before
public void setUp() {

    Funeral funeral1 = new Funeral(Date.from(Instant.now()),
            "Nitardy Funeral Home", "Jack");
    Funeral funeral2 = new Funeral(Date.from(Instant.now()),
            "Dunlap Memorial Home", "Cindie");
    Funeral funeral3 = new Funeral(Date.from(Instant.now()),
            "Olsen Funeral Home", "Perry");

    funerals = Lists.newArrayList(funeral1, funeral2, funeral3);
}

Serialize arraylist to xml

Using the funerals list we will marshal it to xml. Initializing XStream object, a simple facade to the xstream library, we will call toXML passing in the arraylist which will convert the object to xml where will pretty print xml as a string.

@Test
public void serialize_object_to_xml() {

    XStream xStream = new XStream();

    String funeralsAsXML = xStream.toXML(funerals);

    logger.info(funeralsAsXML);

    assertNotNull(funeralsAsXML);
}

Output

<list>
  <com.levelup.java.xml.XMLToArrayListXstream_-Funeral>
    <date>2014-08-21 22:03:30.367 UTC</date>
    <funeralHome>Nitardy Funeral Home</funeralHome>
    <person>Jack</person>
    <outer-class>
      <funerals reference="../../.."/>
    </outer-class>
  </com.levelup.java.xml.XMLToArrayListXstream_-Funeral>
  <com.levelup.java.xml.XMLToArrayListXstream_-Funeral>
    <date>2014-08-21 22:03:30.367 UTC</date>
    <funeralHome>Dunlap Memorial Home</funeralHome>
    <person>Cindie</person>
    <outer-class reference="../../com.levelup.java.xml.XMLToArrayListXstream_-Funeral/outer-class"/>
  </com.levelup.java.xml.XMLToArrayListXstream_-Funeral>
  <com.levelup.java.xml.XMLToArrayListXstream_-Funeral>
    <date>2014-08-21 22:03:30.367 UTC</date>
    <funeralHome>Olsen Funeral Home</funeralHome>
    <person>Perry</person>
    <outer-class reference="../../com.levelup.java.xml.XMLToArrayListXstream_-Funeral/outer-class"/>
  </com.levelup.java.xml.XMLToArrayListXstream_-Funeral>
</list>

Deserialize xml to java arraylist

Taking the xml output above we will unmarshall or deserialize the xml into a java arraylist. As above we will create an XStream object and call fromXML passing in the sample xml.

@Test
public void deserialize_xml_to_arraylist() {

    String rawXML = "<list>...";

    XStream xStream = new XStream();

    List<Funeral> funeral2 = (List<Funeral>) xStream.fromXML(rawXML);

    logger.info(funeral2);

    assertNotNull(funeral2.size() == 2);
}