JAXB and an Attributes Heavy XML File

JAXB, or Java Architecture for XML Binding, is an efficient way to convert XML files to Java Classes and vice versa, but sometimes certain combinations of Elements and Attributes in an XML file can trip you up when defining XML binding in your classes. In this post we’re going to convert the Attributes Heavy CodeJohnny globalproperties.xml file to a CodeJohnnyProperties Collection. It’ll be sweet because when we need to read our collection we’ll do so with a simple


The XML file consists of GlobalProperties root and GlobalProperty elements with only attributes.

We’ll need a CodeJohnnyGlobalProperties class and a CodeJohnnyGlobalProperty class for each < globalproperty /> element.

CodeJohnnyGlobalProperties Class

The JAXB magic in CodeJohnnyGlobalProperties will consist of setting the @XmlRootElement and using a FIELD XmlAccessType. We’ll use a single @XmlElement to define our < globalproperty /> element.

One more interesting tidbit before moving on to CodeJohnnyGlobalProperty is how JAXB uses the getGlobalProperties() getter. This makes populating our List<CodeJohnnyGlobalProperty> collection super easy.

CodeJohnnyGlobalProperty Class

The CodeJohnnyGlobalProperty class requires the @XmlRootElement to be defined and the @XmlAccessType label to match CodeJohnnyGlobalProperties. We will only be using @XmlAttribute labels here which will complete our JAXB assignments. As you see, we’re not assigning any @XmlElements here, only @XmlAttributes.

Where were we? Oh yeah…