how-to

File & Directory

How to use JAXB API - how to store object into XML

For working with JAXB API (Java Architecture for XML Binding) you need to use:

import javax.xml.bind.io.*;
import java.io.File;

With JAXB API you can store object(s) into XML => marshalling , or you can create object from saved XML => unmarshalling.

STEP 1 - class for object

At first you need class for storing to XML:

import javax.xml.bind.annotation.*;

/* -- name for root element */
@XmlRootElement( name = "person1" )
/* -- define order of saved properties */
@XmlType( propOrder={ "name", "age" } )
public class Person {

  public Person() { id = 0; };

  private int id;
  private String name;
  private int age;

  /* -- this property is saved as item attribut (not as element) */
  @XmlAttribute(name = "person_id", required = true)
  public int getId() {
    return id;
  }

  /* -- saved as element */
  @XmlElement
  public String getName() {
    return name;
  }

  /* -- saved as element */
  @XmlElement
  public int getAge() {
    return age;
  }

  public void setId(int id) {
    this.id = id;
  }

  public void setName(String name) {
    this.name = name;
  }

  public void setAge(int age) {
    this.age = age;
  }
}

STEP 2 - creating XML

Now we create instance of JAXB framework and marshaller for output:

/* -- create object */

Person person = new Person();
person.setName( "Jack Howard" );
person.setAge( 35 );
person.setId( 0 );

/* -- create XML output */

try {

  JAXBContext jaxb = JAXBContext.newInstance( Person.class );

  Marshaller marshaller = jaxb.createMarshaller();

  marshaller.setProperty( Marshaller.JAXB_ENCODING, "UTF-8" );
  marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );

  /* -- output to console */
  marshaller.marshal( person, System.out );

  /* -- ouput to file */
  File file = new File( "c:\\test.xml" );
  marshaller.marshal( person, file );

} catch (JAXBException ex) {
  Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}

We have this XML output:

STEP 3 (optional) - loading object from XML

When you have XML, you can recreate from it saved object again:

/* -- prepare file for load */

File file = new File("c:\\test.xml");

try {
  JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);

  /* -- try to read data */
  Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
  Person person = (Person) jaxbUnmarshaller.unmarshal(file);

  /* -- write readed object data */
  System.out.println(person.getName() + ", " + person.getAge());

} catch (JAXBException ex) {
  Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}

When is file correct, the output will be:

Jack Howard, 35