users@jaxb.java.net

Re: JAXB 2.0 default values

From: Ed Mooney <Ed.Mooney_at_Sun.COM>
Date: Tue, 06 Sep 2005 08:49:35 -0400

The default gets assigned when you unmarshal an element with no value:

     xjc.sh test.xsd;javac `find . -name '*.java'`;java test
     parsing a schema...
     compiling a schema...
     testvalue

   -- Ed

Scott Allan wrote:
> Does JAXB 2.0 support the element default attribute?
> for example:
> <xs:element name="test" type="xs:string" default="testvalue"/>
>
> This compiles as such:
> @XmlElement(defaultValue = "testvalue")
> protected String test;
>
> but when I try to read the value, it is null:
>
> MyObject myObject = objFactory.createMyObject();
> System.out.println(myObject.isSetTest());
> System.out.println(myObject.getTest());
>
> false
> null
>
[ ... ]


import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;

public class test {
    public static final void main(final String[] args) {
        try {
            JAXBContext jc = JAXBContext.newInstance("generated");
            Unmarshaller u = jc.createUnmarshaller();
            JAXBElement test = (JAXBElement)u.unmarshal(new File("test.xml"));
            System.out.println(test.getValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}