fun with XML – JAXB and arrays

In part I of my JAXB example I briefly described some of the annotations required to turn normal Java objects into XML files with JAXB.

To expand on the xml examples from my previous post, I will be taking a number of small java objects and load them into an array. What makes this interesting is that the number of XML objects is not known nor all that important when loading or saving.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Library>
    <Publication>
        <Author>Robert Heinlein</Author>
        <Title>Have spacesuit will travel</Title>
        <Price>15.99</Price>
        <Isbn>095524347</Isbn>
    </Publication>
    
     ...

    <Publication>
        <Author>Robert Heinlein</Author>
        <Title>Stranger in a strange land</Title>
        <Price>15.99</Price>
        <Isbn>0123123123</Isbn>
    </Publication>
</Library>

Actually, there isn’t really all that much more that needs to be explained.  The marshal and unmarshal methods converts between xml and plain old java objects.  There is one slight difference.

The top level class is annotated with the @XmlRootElement annotation, then its value is represented as XML element in an XML document.  The actual subobjects or subelements cannot have this tag.

The bookcollection is the top class which is just an array of books which in this case is essentially the primitive.

In my example, the bookcollection is perhaps not a clean separation between the actual xml object and the methods that use it.  All of the methods that are part of this class are not necessary.  The only important part of the class is the following lines.

package de.companyname.complex;

import javax.xml.bind.annotation.*;
import org.apache.log4j.Logger;

@XmlRootElement(name="Library")
@XmlAccessorType(XmlAccessType.FIELD)

public class bookcollection {

	@XmlElement(name="Publication")
	private book[] cardcatalog;

	...

The example is pretty straight forward to understand.  It loads the xml data and dumps it to the console.

This entry was posted in programming and tagged , . Bookmark the permalink.