Java Reference
In-Depth Information
name()
attribute that allows you to specify the exact name of the XML attribute within the
XML document. By default, it is the same name as the annotated field.
In our example, the
@javax.xml.bind.annotation.XmlElement
annotation was placed on
the
fullname
field of our
Customer
class. This annotation tells JAXB to map the field to a
<fullname>
element within the main
<Customer>
element of the XML document.
@XmlEle-
ment
does have a
name()
attribute, so you can specify the exact string of the XML element.
By default, it is the same name as the annotated field.
If we were to output an instance of our
Customer
class that had an
id
of 42 and a
name
of
“Bill Burke,” the outputted XML would look like this:
<customer
<customer id=
"42"
>
<fullname>
<fullname>
Bill Burke
</fullname>
</fullname>
</customer>
You can also use the
@XmlElement
annotation to embed other JAXB-annotated classes. For
example, let's say we wanted to add an
Address
class to our
Customer
class:
@XmlRootElement
(
name
=
"address"
)
@XmlAccessorType
(
XmlAccessType
.
FIELD
)
public
public class
class
Address
Address
{
@XmlElement
protected
protected
String street
;
@XmlElement
protected
protected
String city
;
@XmlElement
protected
protected
String state
;
@XmlElement
protected
protected
String zip
;
// getters and setters
...
}
We would simply add a field to
Customer
that was of type
Address
as follows:
@XmlRootElement
(
name
=
"customer"
)
@XmlAccessorType
(
XmlAccessType
.
FIELD
)
public
public class
class
Customer
Customer
{