15-Jun-17 (Created: 15-Jun-17) | More in 'Old Jaxb 2.0 Tutorial 2014'

jaxb 2.0 tutorial: Java Driver

Manage this page

1. Back to tutorial

Although quite old, this file is still useful.

package com.ai.xml.jaxb20;

import java.io.File;
import java.util.*;
import javax.xml.bind.*;
public class XmlTest 
{
   private static JAXBContext jc = null;
   public static void main(String[] args) 
   {
      try
      {
	 //Create a java object
         Content c = createContent();
		 
	 //Establish a jaxb context
         System.out.println("Establish the context");
         jc = JAXBContext.newInstance(c.getClass());
         //jc = JAXBContext.newInstance("com.ai.xml.jaxb20");
		 
         //Get a marshaller
         Marshaller m = jc.createMarshaller();
		 
	 //Enable formatted xml output
         m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
		 
	 //Marshal to system output: java to xml
         m.marshal(c,System.out);
         
         //Read xml into a java object
         xmlToJava(jc);
         
      }
      catch (JAXBException x)
      {
         x.printStackTrace();
      }
   
   }//eof-main

   public static void xmlToJava(JAXBContext jc)
               throws JAXBException
   {
      //Get an unmarshaller
      Unmarshaller um = jc.createUnmarshaller();
	  
      //Unmarshall the file into a content object
      Object o = um.unmarshal(new File("E:\\satya\\webapps\\jaxb20\\xml\\content.xml"));
      Content c = (Content)o;
	  
      //Remarshal it to system.out to see what you have read
      Marshaller m = jc.createMarshaller();
      m.marshal(c,System.out);
   }
   
   static public Content createContent()
   {
      Content c = new Content();
      Folder f1 = new Folder("f1");
      f1.addFile(new FileItem("f1","f1-de","f1-con"));
      f1.addFile(new FileItem("f2","f2-de","f2-con"));
      c.add(f1);
      return c;
   }
}//eof-class