As an exception, JAXB does not allow null
lists when marching. So instead of using the @XmlElementWrapper(name = "titles")
annotation, you can create a wrapper class that you use in the containing class to save the XmnlTitle
list. If you look like xjc
generated classes, you will find that this is exactly how it handles wrapped list items.
JAXB also automatically skips items that are null
, so you were able to not display the list by returning null
when size() == 0
Packing:
public class XmlTitleWrapper { private List<XmlTitle> title; public void setTitle(List<XmlTitle> title) { this.title = title; } @XmlElement(name = "title") public List<XmlTitle> getTitle() { if(title == null) { title = new ArrayList<XmlTitle>(); } return title; } @Override public String toString() { return "XmlTitleWrapper [title=" + title + "]"; } }
Container:
@XmlRootElement public class Container { private XmlTitleWrapper titles; @XmlElement(name = "titles") public XmlTitleWrapper getTitles() { return titles; } public void setTitles(XmlTitleWrapper titles) { this.titles = titles; } @Override public String toString() { return "Container [titles=" + titles + "]"; } }
Test:
Container c1 = new Container(); List<XmlTitle> title = Arrays.asList(new XmlTitle("A"), new XmlTitle("B")); XmlTitleWrapper wrapper = new XmlTitleWrapper(); wrapper.setTitle(title); c1.setTitles(wrapper); StringWriter writer = new StringWriter(); JaxbUtil.toXML(c1, writer); System.out.printf("%s%n", String.valueOf(writer));
this will generate:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <container> <titles> <title> <value>A</value> </title> <title> <value>B</value> </title> </titles> </container>
If you remove the line setting, the wrapper
c1.setTitles(wrapper);
leaving it null
in the container, then the output will be:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <container/>
source share