We will learn how to write information stored in Java objects fields into XML file or String.
Java Object to XML String Conversion:
import java.io.File;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JaxbObjectToXmlString
{
public static void main(String[] args)
{
//Java object. We will convert it to XML.
Employee employee = new Employee(1, "Rohit", "Sharma", new Department(100, "CS"));
//Method which uses JAXB to convert object to XML
jaxbObjectToXML(employee);
}
private static void jaxbObjectToXML(Employee employee)
{
try
{
//Create JAXB Context ( provides methods to unmarshal, marshal and validate operations)
JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
//Create Marshaller ( provides marshal() method marshals Java object into XML)
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//For Formating
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//For Printing XML String to Console
StringWriter sw = new StringWriter();
//Write XML data to StringWriter
jaxbMarshaller.marshal(employee, sw);
//Verify the XML Content
String xmlData = sw.toString();
System.out.println(xmlData);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
Output
100
CS
Rohit
1
Sharma
Java Object to XML File Conversion:
import java.io.File;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JaxbObjectToXmlFile
{
public static void main(String[] args)
{
//Java object. We will convert it to XML.
Employee employee = new Employee(1, "Rohit", "Sharma", new Department(100, "CS"));
//Method which uses JAXB to convert object to XML
jaxbObjectToXML(employee);
}
private static void jaxbObjectToXML(Employee employee)
{
try
{
//Create JAXB Context ( provides methods to unmarshal, marshal and validate operations)
JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
//Create Marshaller ( provides marshal() method marshals Java object into XML)
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
//For Formating
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//Store XML to File
File f = new File("employee.xml");
//Write XML data to StringWriter
jaxbMarshaller.marshal(employee, f);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
Output
employee.xml
100
CS
Rohit
1
Sharma