users@jaxb.java.net

Request for adding nillable to _at_XmlRootElement

From: Jin Kwon <onacit_at_mac.com>
Date: Sat, 04 Aug 2012 00:07:04 +0900

There folks.

Is there any possibility for adding nillable element to @XmlRootElement?

public class XmlValueTest {

     public static void main(final String[] args) throws JAXBException {

         final JAXBContext context =
             JAXBContext.newInstance(Wrapper.class, Value.class);

         final Marshaller marshaller = context.createMarshaller();
         marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);

         marshaller.marshal(Value.newInstance(null), System.out);
         marshaller.marshal(Value.newInstance("null"), System.out);
         marshaller.marshal(Wrapper.newInstance(null), System.out);
         marshaller.marshal(Wrapper.newInstance("null"), System.out);
     }
}

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement
class Value {

     public static Value newInstance(final String raw) {
         final Value instance = new Value();
         instance.raw = raw;
         return instance;
     }

     @XmlValue
     private String raw;
}

@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement
class Wrapper {
     public static Wrapper newInstance(final String raw) {
         final Wrapper wrapper = new Wrapper();
         wrapper.raw = raw;
         return wrapper;
     }
     @XmlElement(nillable = true, required = true)
     private String raw;
}

prints

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<value/>

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<value>null</value>

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<wrapper>
     <raw xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:nil="true"/>
</wrapper>

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<wrapper>
     <raw>null</raw>
</wrapper>


Adding nillable element on @XmlRootElement can make the first output

<value/>

look like

<value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:nil="true"/>

Thanks.