Java HTML / XML How to - Unmarshall Empty List Java Object








Question

We would like to know how to unmarshall Empty List Java Object.

Answer

//from   w w  w  .  ja v  a2 s .  c  o m
import java.io.File;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

public class Main {

  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Root.class);

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    File xml = new File("input.xml");
    Root root = (Root) unmarshaller.unmarshal(xml);

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(root, System.out);
  }

  @XmlRootElement
  public static class Root {

    private List<String> list;
    private List<String> nestedList;

    @XmlElement(name = "item")
    public List<String> getList() {
      return list;
    }

    public void setList(List<String> list) {
      this.list = list;
    }

    @XmlElementWrapper(name = "items")
    @XmlElement(name = "item")
    public List<String> getNestedList() {
      return nestedList;
    }

    public void setNestedList(List<String> nestedList) {
      this.nestedList = nestedList;
    }

  }
}

input.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>/*  w ww . ja  v a 2s.c  o m*/
    <item>A</item>
    <item>B</item>
    <item>C</item>
    <items>
        <item>D</item>
        <item>E</item>
        <item>F</item>
    </items>
</root>