Provided that XML lets you represent a data item as a single value, there is no cut-and-dried rule for deciding between using an element or an attribute. (If you look for guidance, the schema describing the XML Schema language itself, making judicious use of both, is a good example.) JAXB, of course, has to be told when to make a field into an XML attribute.
The annotation for creating an XML attribute is XmlAttribute
. Its elements correspond to what can be defined in an XML schema:
name
defines the namestring for the attribute, the default being the class field's name.namespace
specifies the XML target namespace to be used for the attribute's name.- A "true" value of
required
is the same as using the XML Schema definition's attributeuse="required"
.
If you ask about some way for defining the equivalent for the XML Schema attribute default="
value"
, then the simple answer is: "Do it yourself." Just write the getter so that it returns the default value if the field's value is null.
It's possible to annotate a static final field with XmlAttribute
. This has the same effect as an XML Schema definition where the attribute element's attribute fixed
is set to that value.
@XmlAttribute final static int answer = 42;