Java Reference
In-Depth Information
@XmlAttribute
protected
protected int
int id ;
@XmlElement
protected
protected String name ;
@XmlElement
protected Address address ;
public
public Customer () {}
public
public int
int getId () { return
return this
this . id ; }
public
public void
void setId ( int
int id ) { this
this . id = id ; }
...
}
If we were to output an instance of our new Customer class that had an id of 42, a name of
“Bill Burke,” a street of “200 Marlborough Street,” a city of “Boston,” a state of “MA,”
and a zip of “02115,” the outputted XML would look like this:
<customer
<customer id= "42" >
<name>
<name> Bill Burke </name>
</name>
<address>
<address>
<street>
<street> 200 Marlborough Street </street>
</street>
<city>
<city> Boston </city>
</city>
<state>
<state> MA </state>
</state>
<zip>
<zip> 02115 </zip>
</zip>
</address>
</customer>
</address>
</customer>
There are a number of other annotations and settings that allow you to do some more com-
plex Java-to-XML mappings. JAXB implementations are also required to have command-
line tools that can automatically generate JAXB-annotated Java classes from XML schema
documents. If you need to integrate with an existing XML schema, these autogeneration
tools are the way to go.
To marshal Java classes to and from XML, you need to interact with the
javax.xml.bind.JAXBContext class. JAXBContext instances introspect your classes to un-
derstand the structure of your annotated classes. They are used as factories for the
javax.xml.bind.Marshaller and javax.xml.bind.Unmarshaller interfaces. Mar-
shaller instances are used to take Java objects and output them as XML. Unmarshaller in-
stances are used to take XML input and create Java objects out of it. Here's an example of
using JAXB to write an instance of the Customer class we defined earlier into XML and then
to take that XML and re-create the Customer object:
Search WWH ::




Custom Search