Sunday, 27 September 2015

JAXB Convert Object to XML String

JAXB Marshalling - Converts Java Object to XML. 

You need to JAXB library jar , download from here.

Really JAXB makes developers life easy and help to develop stable and reliable coding. Below Example shows how to convert the Java object into XML format.

package com.javadevelopersguide;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
public class Book {
private String name;
private String author;
private String price;
public String getName() {
return name;
public void setName(String name) { = name;
public String getAuthor() {
return author;
public void setAuthor(String author) { = author;
public String getPrice() {
return price;
public void setPrice(String price) {
this.price = price;

package com.javadevelopersguide;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
 * @author Manoj
public class JAXBObjectToXML {
* @param args
public static void main(String[] args) {
Book book=new Book();
book.setAuthor("M Bardhan");
book.setName("Java Cookbook");
try {
JAXBContext jaxbContext=JAXBContext.newInstance(Book.class);
Marshaller marshaller=jaxbContext.createMarshaller();
marshaller.marshal(book, System.out);
} catch (JAXBException e) {
System.out.println("Error occured ::"+e.getMessage());

Output XML :-

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <author>M Bardhan</author>
    <name>Java Cookbook</name>

Hope it will help you.

Follow for more details on Google+ and @Facebook!!!