tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 XML > JAXB > Serialize Enum to XML

Serialize Enum to XML 

The following example shows serializing Enum to an XML. The Enum should be annotated with @XmlRootElement annotation.

File Name  :  
com/bethecoder/tutorials/jaxb/common/ServerStatus.java 
   
package com.bethecoder.tutorials.jaxb.common;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public enum ServerStatus {

  START("Server is starting"),
  RUNNING("Server is running"),
  STOP("Server is stopping");
  
  private String status;
  
  ServerStatus(String status) {
    this.status = status;
  }

  public String getStatus() {
    return status;
  }

  public String toString() {
    return name() " -> " + getStatus();
  }
}
   

File Name  :  
com/bethecoder/tutorials/jaxb/tests/EnumToXML.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.jaxb.tests;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.bethecoder.tutorials.jaxb.common.ServerStatus;

public class EnumToXML {

  public static void main (String [] argsthrows JAXBException {
    
    /**
     * Create JAXB Context from the classes to be serialized
     */
    StringWriter output = new StringWriter();
    JAXBContext context = JAXBContext.newInstance(ServerStatus.class);  
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);  
    m.marshal(ServerStatus.START, output);  
    System.out.println(output.toString());
    
    /**
     * Unmarshall
     */
    Unmarshaller um = context.createUnmarshaller();
    StringReader sr = new StringReader(output.toString());
    ServerStatus serverStatus = (ServerStatusum.unmarshal(sr);
    System.out.println("Status : " + serverStatus);
  }
}
   

It gives the following output,
File Name  :  OUTPUT


                    Print

   



Books Recommendation

 
 
bl  br