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

Serialize Binary data to XML 

The following example shows serializing a POJO with binary data to an XML. The POJO should have a no-arg default constructor and @XmlRootElement annotation at class level.

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

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class BinaryData {

  private byte [] data;

  public byte[] getData() {
    return data;
  }

  public void setData(byte[] data) {
    this.data = data;
  }
  
}
   

File Name  :  
com/bethecoder/tutorials/jaxb/tests/BinaryToXML.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.BinaryData;

public class BinaryToXML {

  public static void main (String [] argsthrows JAXBException {
    
    BinaryData binaryData = new BinaryData();
    binaryData.setData("BE THE CODER".getBytes());  //encoded in xs:base64Binary by default
    
    /**
     * Create JAXB Context from the classes to be serialized
     */
    StringWriter output = new StringWriter();
    JAXBContext context = JAXBContext.newInstance(BinaryData.class);  
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);  
    m.marshal(binaryData, output);  
    System.out.println(output.toString());
    
    /**
     * Unmarshall
     */
    Unmarshaller um = context.createUnmarshaller();
    StringReader sr = new StringReader(output.toString());
    binaryData = (BinaryDataum.unmarshal(sr);
    System.out.println("Data decoded : " new String(binaryData.getData()));

  }
}
   

It gives the following output,
File Name  :  OUTPUT


                    Print

   



Books Recommendation

 
 
bl  br