javacodex.com
Java Examples
Java Examples
memu home questions

JAXB Convert XML To Java Object

Source: (JAXBExample.java)

import java.io.*;
import javax.xml.bind.*;
import javax.xml.bind.annotation.*;
 
public class JAXBExample {
   public static void main(String[] args) {
 
   try {
 
      File file = new File("./book.xml");
      JAXBContext context = JAXBContext.newInstance(Book.class);
 
      Unmarshaller unmarshaller = context.createUnmarshaller();
      Book book = (Book) unmarshaller.unmarshal(file);
      System.out.println("ID: " + book.getId());
      System.out.println("Name: " + book.getName());
      System.out.println("Autho: " + book.getAuthor());
 
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}
 
@XmlRootElement
class Book {
 
   int id;
   String name;
   String author;
 
   public int getId() {
      return id;
   }
 
   @XmlAttribute
   public void setId(int id) {
      this.id = id;
   }
 
   public String getName() {
      return name;
   }
 
   @XmlElement
   public void setName(String name) {
      this.name = name;
   }
 
   public String getAuthor() {
      return author;
   }
 
   @XmlElement
   public void setAuthor(String author) {
      this.author = author;
   }
}
 

Output:

$ cat book.xml 
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book id="101">
    <author>Mark Twain</author>
    <name>Adventures of Huckleberry Finn</name>
</book>

$ java JAXBExample 
ID: 101
Name: Adventures of Huckleberry Finn
Autho: Mark Twain

Contact: javacodex@yahoo.com