prev | table of contents | next |
XML can express the absence of a value in different ways. Let's look at the complex type defined like this:
<xsd:complexType name="DemoType"> <xsd:sequence> <xsd:element name="A" type="xsd:string"/> <xsd:element name="B" type="xsd:string" minOccurs="0"/> <xsd:element name="C" type="xsd:string" nillable="true"/> </xsd:sequence> </xsd:complexType>Element
<A>
must be present, even though its value
could be the empty string, the characterless thing. However, using
the empty string as an indication for the absence of a value is,
in general, not a good idea. A better
solution is provided by the definition of element <B>
,
where its absence can be expressed by simply omitting it from its
parent element, in accordance with the attribute minOccurs="0"
.
Yet another possibility is shown with element <C>
,
which can not be omitted, but its attribute
nillable="true"
permits the usage of an XML element
that doesn't even contain the empty string but uses the attribute
xsi:nil
, as shown in this valid example for a
DemoType
element: (The prefix xsi
must be bound to
http://www.w3.org/2001/XMLSchema-instance
.)
<demo> <A></A> <!-- no element <B> here --> <C xsi:nil="true"/> </demo>
The declarations, and the getters and setters for all three fields are identical. JAXB distinguishes between the three representations by attaching suitable annotations. Although we are going to discuss annotations in more detail later on, we'll have a peek at the crucial ones right now.
public class DemoType { @XmlElement(name = "A", required = true) protected String a; @XmlElement(name = "B") protected String b; @XmlElement(name = "C", required = true, nillable = true) protected String c; public String getA() { return a; } public void setA(String value) { this.a = value; } // ... (more getters and setters like this) }
prev | table of contents | next |