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.
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.
The example is pretty straight forward to understand. It loads the xml data and dumps it to the console.
bookcollection.java
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;
public book[] getCatalog()
{
return cardcatalog;
}
public void setCatalog(book cardCatalog[])
{
cardcatalog = cardCatalog;
}
public int itemCount()
{
int len = 0;
if (cardcatalog == null)
len = 0;
else
len = cardcatalog.length;
return len;
}
public book findBook(String title)
{
book retval = null;
Logger logfile = Logger.getLogger(bookcollection.class);
logfile.debug("looking for book" );
for (int idx = 0; idx < cardcatalog.length; idx++)
{
logfile.debug(cardcatalog[idx].getTitle() + " ");
logfile.debug(cardcatalog[idx].getAuthor() + " ");
logfile.debug(cardcatalog[idx].getPrice() + " ");
logfile.debug(cardcatalog[idx].getISBN() );
logfile.debug("");
if (cardcatalog[idx].getTitle().equalsIgnoreCase(title) )
{
return cardcatalog[idx];
}
}
logfile.error("unable to locate publication '" + title + "' ");
return retval;
}
}
book.java
The book class has a main method which is completely unnecessary for the “libraryapplication”, it was added when I was testing the book object.
package de.companyname.complex;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class book {
// Microsoft Exchange values
@XmlElement(name="Author")
private String author;
@XmlElement(name="Title")
private String title;
@XmlElement(name="Price")
private double price;
@XmlElement(name="Isbn")
private String isbn;
public book()
{
}
public book(String author, String title, double price, String isbn)
{
this.author = author;
this.title = title;
this.price = price;
this.isbn = isbn;
}
public String getAuthor()
{
return author;
}
public void setAuthor(String value)
{
this.author = value;
}
public String getTitle()
{
return title;
}
public void setTitle(String value)
{
this.title = value;
}
public double getPrice()
{
return price;
}
public void setPrice(double value)
{
this.price = value;
}
public String getISBN()
{
return isbn;
}
public void setISBN(String value)
{
this.isbn = value;
}
public void dump()
{
JAXBContext jc = null;
try {
jc = JAXBContext.newInstance(book.class);
}
catch (JAXBException ex)
{
// TODO Auto-generated catch block
ex.printStackTrace();
}
Marshaller marshaller;
try {
marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(this, System.out);
}
catch (JAXBException ex)
{
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
public book load(String filename)
{
book loaded = new book();
JAXBContext jc = null;
try {
jc = JAXBContext.newInstance(book.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File(filename);
loaded = (book) unmarshaller.unmarshal(xml);
}
catch (JAXBException ex)
{
// TODO Auto-generated catch block
ex.printStackTrace();
}
return loaded;
}
public void save(String filename)
{
JAXBContext jc = null;
try {
jc = JAXBContext.newInstance(book.class);
}
catch (JAXBException ex)
{
// TODO Auto-generated catch block
ex.printStackTrace();
}
Marshaller marshaller;
try {
marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
OutputStream os = new FileOutputStream( filename );
marshaller.marshal( this, os );
os.close();
}
catch (JAXBException ex)
{
// TODO Auto-generated catch block
ex.printStackTrace();
}
catch (FileNotFoundException ex)
{
// TODO Auto-generated catch block
ex.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
book single = new book ();
single.setTitle("bible");
single.setISBN("0000");
single.setPrice(9.99);
single.setAuthor("Jesus");
single.dump();
single.save("first.xml");
book second = single.load("first.xml");
second.dump();
}
}
libraryapplication.java
The loadCatalog and saveCatalog methods do the necessary marshalling between the xml and the plain old java objects.
package de.companyname.complex;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class libraryapplication
{
private bookcollection cardcatalog = null;
public void dump()
{
JAXBContext jc = null;
try {
jc = JAXBContext.newInstance(bookcollection.class);
}
catch (JAXBException ex)
{
// TODO Auto-generated catch block
ex.printStackTrace();
}
Marshaller marshaller;
try {
marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(cardcatalog, System.out);
}
catch (JAXBException ex)
{
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
public void loadCatalog(String filename)
{
File file = new File("./",filename);
if (file.exists() == true)
{
JAXBContext jaxbContext = null;
Unmarshaller jaxbUnmarshaller = null;
try {
jaxbContext = JAXBContext.newInstance(bookcollection.class);
jaxbUnmarshaller = jaxbContext.createUnmarshaller();
cardcatalog = (bookcollection) jaxbUnmarshaller.unmarshal(file);
}
catch (JAXBException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
cardcatalog = new bookcollection();
}
}
else
{
cardcatalog = new bookcollection();
}
}
public void saveCatalog(String filename)
{
File file = new File("./",filename);
JAXBContext jc = null;
try {
jc = JAXBContext.newInstance(bookcollection.class);
}
catch (JAXBException ex)
{
// TODO Auto-generated catch block
ex.printStackTrace();
}
Marshaller marshaller;
try {
marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
OutputStream os = new FileOutputStream( file );
marshaller.marshal( cardcatalog, os );
os.close();
}
catch (JAXBException ex)
{
// TODO Auto-generated catch block
ex.printStackTrace();
}
catch (FileNotFoundException ex)
{
// TODO Auto-generated catch block
ex.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void createCatalog(String filename)
{
cardcatalog = new bookcollection();
book list[] = new book[1];
list[0] = new book("Robert Heinlein","Stranger in a strange land",15.99, "0123123123");
cardcatalog.setCatalog(list);
saveCatalog(filename);
}
/**
* @param args
*/
public static void main(String[] args)
{
String libraryName = "US-LibraryOfCongres.xml";
libraryapplication libraryofcongress = new libraryapplication();
// create a list
libraryofcongress.createCatalog("deutsche-bibliothek.xml");
libraryofcongress.dump();
// create a list
libraryofcongress.createCatalog("britsh-library.xml");
libraryofcongress.dump();
// load a list
libraryofcongress.loadCatalog(libraryName);
libraryofcongress.dump();
}
}