- JAXB is for converting java pojo to xml.
- It Supports annotation too.
- In jdk 1.6 and above it is aready package inside.
- For less then jdk 1.6 , download from link:-
Project Structure :-
Fruit Java Pojo:-
package com.sandeep.jaxb.demo;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Fruit {
private String name;
private int cost;
private String unit;
public String getUnit() {
return unit;
}
@XmlAttribute
public void setUnit(String unit) {
this.unit = unit;
}
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getCost() {
return cost;
}
@XmlElement
public void setCost(int cost) {
this.cost = cost;
}
}
Fruit Data Service:-
package com.sandeep.jaxb.demo;
public class FruitDataService {
public static Fruit getFruits(){
Fruit aFruit = new Fruit();
aFruit.setName("Mango");
aFruit.setUnit("Kg");
aFruit.setCost(100);
return aFruit;
}
}
Test JAXB Parser:-
package com.sandeep.jaxb.demo;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.PropertyException;
public class TestJaxbDemo {
public static void main(String[] args) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Fruit.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Fruit aFruit=FruitDataService.getFruits();
jaxbMarshaller.marshal(aFruit, System.out);
} catch (PropertyException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
}
}
}