logo

Creating JAXB classes from scratch

If you have XSD file, the easiest way how to create JAXB classes is to generate them. If you don't have XSD, you can just simply write them from scratch.

If you have XSD file, the easiest way how to create JAXB classes is to generate them. If you don't have XSD, you can just simply write them from scratch. There's just one thing you need to do, otherwise it won't work and that's annotation @XmlRootElement in your JAXB class, which is an XML root element.

 

Suppose you have this XML file with information who attended some training:

 

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<training>
  <name>Java Training</name>
  <person id="1">
    <name>George</name>
  </person>
  <person id="2">
    <name>Michael</name>
  </person>
</training>

 

Inside is a single tag name and multiple person tags. Let's create a Training class:

 

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Training {
 
  @XmlElement(name = "person")
  private List<Person> persons;
 
  private String name;
 
  public List<Person> getPersons() {
    return persons;
  }
 
  public void setPersons(List<Person> persons) {
    this.persons = persons;
  }
 
  public String getName() {
    return name;
  }
 
  public void setName(String name) {
    this.name = name;
  }
 
}

 

And now let's create a Person class:

 

@XmlAccessorType(XmlAccessType.FIELD)
public class Person {
 
  @XmlAttribute
  private int id;
 
  private String name;
 
  public String getName() {
    return name;
  }
 
  public void setName(String name) {
    this.name = name;
  }
 
  public int getId() {
    return id;
  }
 
  public void setId(int id) {
    this.id = id;
  }
}

 

 

And some test code:

 

    JAXBContext jaxbContext = JAXBContext.newInstance(Training.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    Training training = (Training) unmarshaller.unmarshal(new File("persons.xml"));
    System.out.println("training name: " + training.getName());
    
    List<Person> persons = training.getPersons();
    for (Person person : persons) {
      System.out.println(person.getName() + ", id: " + person.getId());
    }

 


comments powered by Disqus

rss

Free online Java web application examples

Want to develop whole web applications which use database, security and more? See my github account, where are lot's of example projects:
github

Search