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.

Book.java



package com.javadevelopersguide;

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.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");
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>



Hope it will help you.

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





No comments:

Post a Comment