如何在JAXB XML编组中显示空列表?

问题描述:

嗨我正在使用JAXB(JAVA)编组XML。如何在JAXB XML编组中显示空列表?

我有一些有时大小为零的XmlList元素。

由于它构造实际的数组列表时吸气剂被调用时,

输出总是显示空元素,如

<aa></aa> 

反正是有消除这些“空”元素?

谢谢。

+0

我猜 - 让您的收藏空的,而不是空。 – john

+0

像单身人士的懒惰初始化。第一次插入时,让你的类负责创建一个'List'的实例,一旦创建就使用相同的。同样,从列表中删除也应该谨慎。 – soufrk

+0

出于某种原因,我生成的源getter具有如下 公开列表 getPointOfAccess(){ if(pointOfAccess == null){ pointOfAccess = new ArrayList (); } return this.pointOfAccess; } –

public void representingNullAndEmptyCollections() throws Exception { 
    JAXBContext jc = JAXBContext.newInstance(Root.class); 

    Root root = new Root(); 

    root.nullCollection = null; 

    root.emptyCollection = new ArrayList<String>();// Shows a Empty Element 

    root.populatedCollection = new ArrayList<String>(); 
    root.populatedCollection.add("foo"); 
    root.populatedCollection.add("bar"); 

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

一般null字段不是由JAXB呈现。诀窍是使用一个特殊的getter。

人们普遍简单:

public List<String> getStuff() { 
    return stuff.isEmpty() ? null : stuff; 
}