Java Architecture for XML Binding (JAXB) provides a fast and convenient way to bind XML schemas and Java representations, making it easy for Java developers to incorporate XML data and processing functions in Java applications. As part of this process, JAXB provides methods for unmarshalling (reading) XML instance documents into Java content trees, and then marshalling (writing) Java content trees back into XML instance documents. ”  oracle

In this tutorial we will make  a class representing a simple person object. Furthermore we will code the class Persons wich holds a list of Person. We could also just write a simple person object to the xml file and retrieve it but this is in most cases not the real world scenario. Thus we will marshall (write) and unmarshall (read) the whole list to and from an xml file.

The Person class

Have a look at the code first

package model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "person")
@XmlAccessorType (XmlAccessType.FIELD)
public class Person
{
private String username;
private String firstName;
private String password;
private String email;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

there is  nothing much to explain at this point. But lets look at the annotations we are using here

  • @XmlRootElement: this annotation maps a class or an enum type to an XML element.  In our case the whole class
  • XML AccesorType: This controls which fields or javabean properties are serialized by default. In other words wich fields will be written to our XML File. In this case we choose to write every non static, non transient fields to the xml file

The Persons class

Have a look at the code first

package model;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "persons")
@XmlAccessorType (XmlAccessType.FIELD)
public class Persons<T extends Person>
{
@XmlElement(name = "person")
private List<T> persons = null;
public List<T> getPersons() {
return persons;
}
public void setPersons(List<T> persons) {
this.persons = persons;
}
}

I choose to make this class generic it doesnt matter for this tutorial. Furthermore we used the same annotations. This translates to the following.
We have one xml node persons (look how we named it name=”persons” in the forst annotation) which can contain for zero to many person objects.

Writing to XML with JAXB

Have a look at the code first and make sure you have an empty xml file somewhere to write our data in. You will need the filepath from it so copy it already

 

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.xml.sax.XMLReader;
import model.Person;
import model.Persons;
//Initialize the employees list
public class XmlWriter {
static Persons employees = new Persons();
static {
employees.setPersons(new ArrayList<Person>());
// Create two employees
Person emp1 = new Person();
emp1.setEmail("can@gmail.com");
emp1.setFirstName("Can");
emp1.setPassword("MyPassword");
emp1.setUsername("Cang18");
Person emp2 = new Person();
emp2.setEmail("Djer@gmail.com");
emp2.setFirstName("Daniel");
emp2.setPassword("PasswortVonDaniel");
emp2.setUsername("Djerun");
// Add the persons in list
employees.getPersons().add(emp1);
employees.getPersons().add(emp2);
}
/*
* This Value is used to retrieve a List of Type Person saved in a XML File
* @throws JAXBExeption
*/
private static void marshallingPersons() throws JAXBException {
//
JAXBContext jaxbContext = JAXBContext.newInstance(Persons.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Marshall (write) the objects to the xml file
jaxbMarshaller.marshal(employees, new File("C:\\Users\\GUC\\Desktop\\person.xml"));
}
}

Okay first things first. We obviously created 2 person objects which we put in the persons list. Nothing special here. But what happened next?

  • We defined the method marshallingPersons which handles the writing to xml
  • We instantiated  a JAXBContext object (with a factory pattern method)  which uses ur Persons class info for managing the binding Information necessary for operations like read and write
  • Then we created the Marshaller using our context. The Marshaller will do the whole writing/serializing stuff
  • We specified that our XML data is formatted with linefeeds and indentation
  • We told our marshaller to marsahl()

No try out our code in a main method to see if it works (it should)

public static void main(String[] args) throws JAXBException {
marshallingPersons();
}

Your XML File should be filled with content now

Reading from XML with JAXB

Have a look at the code first

import java.io.File;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import model.Person;
import model.Persons;
public class XmlReader {
/*
* This Value is used to retrieve a List of Type Person saved in a XML File
* @param filePath of the persons.xml
* @return List of Persons
* @throws JAXBExeption
*/
public static List<Person> unMarshalingPersonXml(String filePath) throws JAXBException
{
JAXBContext jContext = JAXBContext.newInstance(Persons.class);
Unmarshaller jUnmarshaller = jContext.createUnmarshaller();
Persons unmarshaledList = (Persons) jUnmarshaller.unmarshal(new File(filePath));
return unmarshaledList.getPersons();
}
}

I think i have nothing to add here. It is merely the same but in reverse

No try out our code in a main method to see if it works (it should (again))

public static void main(String[] args) throws JAXBException {
List<Person> unMarshalingPersonXml = XmlReader.unMarshalingPersonXml("C:\\Users\\GUC\\Desktop\\person.xml");
for (Person person : unMarshalingPersonXml) {
System.out.println(person.getFirstName());
}
}

The output should be: Can, Daniel

Spread the love