Showing posts with label Marshalling. Show all posts
Showing posts with label Marshalling. Show all posts

Sunday, September 27, 2015

JAXB Marshalling: Convert Java Object to XML

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.

Book.java

package com.techbyteslearn;

 

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Book {
private String name;
private String author;
private String price;
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;
}
public String getPrice() {
return price;
}
@XmlElement
public void setPrice(String price) {
this.price = price;
}
}

JAXBObjectToXML.java


package com.techbyteslearn;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBObjectToXML {
/**
* @param args
*/
public static void main(String[] args) {
Book book=new Book();
book.setAuthor("M Bardhan");
book.setName("Java Cookbook");
book.setPrice("$200");
try {
JAXBContext jaxbContext=JAXBContext.newInstance(Book.class);
Marshaller marshaller=jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
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"?>
<book>
    <author>M Bardhan</author>
    <name>Java Cookbook</name>
    <price>$200</price>
</book>