JAXB (Java Architecture for XML Binding) is a powerful framework that simplifies the process of mapping Java objects to XML and vice versa. It provides a convenient way to serialize Java objects into XML format and deserialize XML back into Java objects.
JAXB uses annotations to define how Java objects should be mapped to XML elements. Here are some commonly used annotations:
@XmlRootElement
: Specifies the root element of the XML@XmlElement
: Maps a Java field to an XML element@XmlAttribute
: Maps a Java field to an XML attribute@XmlTransient
: Excludes a field from XML serializationMarshalling is the process of converting Java objects to XML. Here's a simple example:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
@XmlRootElement
public class Person {
private String name;
private int age;
// Getters and setters omitted for brevity
public static void main(String[] args) throws Exception {
JAXBContext context = JAXBContext.newInstance(Person.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Person person = new Person();
person.setName("John Doe");
person.setAge(30);
marshaller.marshal(person, System.out);
}
}
This code will generate XML output like:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<age>30</age>
<name>John Doe</name>
</person>
Unmarshalling is the process of converting XML back to Java objects. Here's an example:
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
public class UnmarshalExample {
public static void main(String[] args) throws Exception {
String xml = "<person><name>Jane Doe</name><age>25</age></person>";
JAXBContext context = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
StringReader reader = new StringReader(xml);
Person person = (Person) unmarshaller.unmarshal(reader);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
JAXB can be seamlessly integrated with other XML technologies in Java, such as:
By leveraging JAXB, developers can significantly reduce the complexity of working with XML in Java applications. Its annotation-based approach and seamless integration with Java objects make it an invaluable tool for XML data binding.