Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
725 views
in Technique[技术] by (71.8m points)

xsd - JAXB objects initialized with default values

There is little problem with JAXB.


Given:

  • Java 1.5; jaxb -jars from jaxws-2_0.
  • .xsd scheme and generated JAXB classes.
  • Every simple element in .xsd has default value. And as result class members has annotations like "@XmlElement(name = "cl_fname", required = true, defaultValue = "[______]")"

Required


Get java object (root element) which fully represent xml and every member initialized by default values.


when I try to marshall xml without explicitly setting values, default values doesn't make sence... is there any way to marshall xml populated with default values without customization of generated classes?

example of .xsd:

<xs:element name="document">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="d_int"/>
            <xs:element ref="d_double"/>
            <xs:element ref="d_string"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

<xs:element name="d_int" type="xs:int" default="-1"/>
<xs:element name="d_double" type="xs:double" default="-1.0"/>
<xs:element name="d_string" type="xs:string" default="false"/>

and java class:

public class Document {
    @XmlElement(name = "d_int", defaultValue = "-1")
    protected int dInt;
    @XmlElement(name = "d_double", defaultValue = "-1.0")
    protected double dDouble;
    @XmlElement(name = "d_string", required = true, defaultValue = "Default")
    protected String dString;
...
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

default value that is in annotations works only after unmarshalling.
unmarshal this

<document>
   <d_int/>
   <d_double/>
   <d_string/>
</document>  

and you will get object with default values (-1, -1.0, "Default")

If you want set default values to marshalling, you should do this

public class Document {
    @XmlElement(name = "d_int", defaultValue = "-1")
    protected int dInt = 100;
    @XmlElement(name = "d_double", defaultValue = "-1.0")
    protected double dDouble = -100;
    @XmlElement(name = "d_string", required = true, defaultValue = "Default")
    protected String dString = "def";
...
}    

jaxb generate default values only for unmarshalling


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...