javacodex.com
Java Examples
Java Examples
memu home questions

JAXB Convert Java Object To XML

This example demonstrates how to use JAXB (Java Architecture for XML Binding) annotation to convert a Java object to a XML file.

Source: (JAXBExample.java)

import java.io.*;
import javax.xml.bind.*;
import javax.xml.bind.annotation.*;
 
public class JAXBExample {
 
   public static void main(String[] args) {
 
   Book book = new Book();
   book.setId(101);
   book.setName("Adventures of Huckleberry Finn");
   book.setAuthor("Mark Twain");
 
   try {
 
      File file = new File("/tmp/book.xml");
      JAXBContext context = JAXBContext.newInstance(Book.class);
      Marshaller marshaller = context.createMarshaller();
 
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
 
      marshaller.marshal(book, file);
      marshaller.marshal(book, System.out);
 
      } 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:

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


$ cat /tmp/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>

Contact: javacodex@yahoo.com