how-to

File & Directory

How to use JAXB API - how to store multiple objects 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.

Storing more objects is a little different, one way is to define a wrapper class, that holds children objects.

STEP 1 - class for object

At first you need class for storing every single objectto XML:

import javax.xml.bind.annotation.*;

/* -- 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 - class that works as a wrapper

Now is important to define class that will holds children objects. For this wrapper we use java.util.ArrayList class.

/* -- here is defined root element name */
@XmlRootElement( name="root" )
static public class ForSaveMultiple {

   private ArrayList<Person> list = new ArrayList<Person>();

   public ArrayList<Person> getList() {
     return list;
   }

   /* -- this element name "wrap" all person record */
   @XmlElementWrapper(name = "persons")

   /* -- this is element name for every person record */
   @XmlElement( name = "person" )
   public void setList(ArrayList<Person> orderDetailList) {
     this.list = orderDetailList;
    }
}

STEP 3 - creating XML

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

/* -- wrapper for multiple record data */
    
ForSaveMultiple forSaveMultiple = new ForSaveMultiple();
     
/* -- create two person records and and them to list */
    
Person person = new Person();
person.setName( "Jack Howard" );
person.setAge( 35 );
person.setId( 0 );
forSaveMultiple.getList().add(person);
    
Person person1 = new Person();
person1.setName( "Anny" );
person1.setAge( 27 );
person1.setId( 1 );
forSaveMultiple.getList().add(person1);
    
/* -- create XML output */

try {
      
  JAXBContext jaxb = JAXBContext.newInstance( ForSaveMultiple.class );

  Marshaller marshaller = jaxb.createMarshaller();
      
  marshaller.setProperty( Marshaller.JAXB_ENCODING, "UTF-8" );
  marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
      
  /* -- output to console */
  marshaller.marshal( forSaveMultiple, System.out );
      
  /* -- ouput to file */
  File file = new File( "c:\\test.xml" );
  marshaller.marshal( forSaveMultiple, file );
                  
} catch (JAXBException ex) {
  Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}

We have this XML output:

STEP 4 (optional) - loading objects from XML

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

/* -- prepare file for load */

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

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

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

  /* -- write readed objects data */
  System.out.println( forSaveMultiple.getList().size() );
  for ( int i = 0; i < forSaveMultiple.getList().size(); i++ )
    System.out.println( forSaveMultiple.getList().get(i).getName() + ", " + forSaveMultiple.getList().get(i).getAge());

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

When is file correct, the output will be:

2
Jack Howard, 35
Anny, 27