JAXB (Java Architecture for XML Binding) API allows us to convert Java Object to XML file or simple XML string.
JAXB Java Object to XML:
JAXB provides two main features – that are marshalling and unmarshalling. Marshalling allows us to convert Java objects to XML whereas unmarshalling used to convert XML to Object.
Here we will see how to marshal an object.
Object to XML Conversion:
Add jaxb-api
dependency in pom.xml.
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- API, java.xml.bind module -->
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.2</version>
</dependency>
<!-- Runtime, com.sun.xml.bind module -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.2</version>
</dependency>
Object to XML String Example:
Creating a Java class, it’s going to be converted to an XML.
Book.java
public class Book {
private int id;
private String name;
private double price;
// constructor
// getters and setters
// tostring
}
Java Object to XML conversion using JAXB marshaller. Here we are simply converting the object to an XML string.
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
public class ObjectToXML {
public static void main(String[] args) {
Book book = new Book(1,"Java",200);
createXML(book);
}
private static void createXML(Book book) {
try
{
JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
StringWriter sw = new StringWriter();
marshaller.marshal(book, sw);
System.out.println(sw.toString());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
Output:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Book>
<id>1</id>
<name>Java</name>
<price>200.0</price>
</Book>
Java Object to XML File Example:
We can also save the converted XML into a physical file using the marshal(Object obj, File location) overloaded method.
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.File;
public class ObjectToXML {
public static void main(String[] args) {
Book book = new Book(1,"Java",200);
createXMLFile(book);
}
private static void createXMLFile(Book book) {
try
{
File file = new File("book.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Book.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(book, file);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
as an output, you can see the generated book.xml in your specified directory.
References:
Happy Learning 🙂