💡 Level Up Your Java Skills with Ram N Java!
Subscribe now for clear explanations, practical coding demos, and end-to-end tutorials.
🔔 Subscribe to YouTube ChannelIntroduction to JAXB
JAXB (Java Architecture for XML Binding) provides a simple and clean API to convert Java objects into XML documents and vice versa. It removes the need for tedious manual parsing with DOM or SAX.
Core Operations in JAXB
- Marshalling: Converting a Java object representation into an XML file or stream.
- Unmarshalling: Reading an XML file or stream and converting it back into a Java object.
Annotations Used in Employee Example
@XmlRootElement: Specifies that theEmployeeclass represents the root element in the generated XML.@XmlAttribute: Configures a property (likeid) to appear as an attribute of the XML root tag.@XmlElement: Maps class fields (likenameandsalary) to child elements within the XML.
Step-by-Step Code Walkthrough
1. Annotated Employee Class
@XmlRootElement(name = "employee")
public class Employee {
private int id;
private String name;
private double salary;
public Employee() {}
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
@XmlAttribute(name = "id")
public int getId() { return id; }
public void setId(int id) { this.id = id; }
@XmlElement(name = "name")
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@XmlElement(name = "salary")
public double getSalary() { return salary; }
public void setSalary(double salary) { this.salary = salary; }
}
2. Marshalling: Java Object to XML
JAXBContext context = JAXBContext.newInstance(Employee.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Employee emp = new Employee(1, "Peter", 50000);
FileOutputStream fos = new FileOutputStream("employee.xml");
marshaller.marshal(emp, fos);
fos.close();
3. Unmarshalling: XML to Java Object
JAXBContext context = JAXBContext.newInstance(Employee.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
File xmlFile = new File("employee.xml");
Employee emp = (Employee) unmarshaller.unmarshal(xmlFile);
System.out.println(emp);
No comments:
Post a Comment