Java Reference
In-Depth Information
@XmlAccessorType ( XmlAccessType . FIELD )
@XmlRootElement ( name = "config" )
We could write the XML schema by hand, using vi or notepad , but regular readers such as
yourself undoubtedly expect that I will refuse to do so whenever possible. Instead, I'll use a
JAXB-provided utility, schemagen , to generate the XML:
$ schemagen -cp $js/target -d /tmp Configuration.java
This generates a schema file with the hardcoded filename schema1.xsd ( .xsd is the normal fi-
lename extension for XML Schema Definition):
<xs:schema
<xs:schema version= "1.0" xmlns:xs= "http://www.w3.org/2001/XMLSchema" >
<xs:element
<xs:element name= "config" type= "configuration" //>
<xs:complexType
<xs:complexType name= "configuration" >
<xs:sequence>
<xs:sequence>
<xs:element
<xs:element name= "screenName" type= "xs:string" minOccurs= "0" //>
<xs:element
<xs:element name= "webProxy" type= "xs:string" minOccurs= "0" //>
<xs:element
<xs:element name= "verbose" type= "xs:boolean" //>
<xs:element
<xs:element name= "colorName" type= "xs:string" minOccurs= "0" //>
</xs:sequence>
</xs:sequence>
</xs:complexType>
</xs:complexType>
</xs:schema>
</xs:schema>
The online source has a commented-up version of this file, renamed to xml.jaxb.xsd .
Now we are ready to serialize or deserialize objects. Example 20-2 shows writing a Config-
uration object out to an XML file and then, some time later in the same program (maybe a
subsequent invocation of the program) reading it back in. This code is written as a JUnit test
(see Avoiding the Need for Debuggers with Unit Testing ) to make it easy to prove that it ac-
tually saves the fields and rereads them.
Example 20-2. JAXB Demonstration Main
// We set up JAXB: the context arg is the package name!
JAXBContext jc = JAXBContext . newInstance ( "xml.jaxb" );
Marshaller saver = jc . createMarshaller ();
final
final File f = new
new File ( "config.save" );
Search WWH ::




Custom Search