Serialize Object to XML Example
This program demonstrates serializing a Java object to XML.
Problem Statement
Write a Java program that serializes a Student object into XML using JAXB.
Source Code
| 1 | import javax.xml.bind.annotation.*; |
| 2 | import javax.xml.bind.*; |
| 3 | @XmlRootElement |
| 4 | class Student { |
| 5 | public int id; public String name; |
| 6 | Student(){} |
| 7 | Student(int id,String name){ this.id=id; this.name=name; } |
| 8 | } |
| 9 | public class XMLSerializeExample { |
| 10 | public static void main(String[] args) throws Exception { |
| 11 | System.out.println("Eduinq XML Serialize Example"); |
| 12 | Student s=new Student(1,"Arun"); |
| 13 | JAXBContext ctx=JAXBContext.newInstance(Student.class); |
| 14 | Marshaller m=ctx.createMarshaller(); |
| 15 | m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); |
| 16 | m.marshal(s,System.out); |
| 17 | } |
| 18 | } |
Program Output
Eduinq XML Serialize Example
<Student>
<id>1</id>
<name>Arun</name>
</Student>
Explanation
Uses JAXB Marshaller to convert object. - Produces XML representation. - Exception handling ensures safe operations. - In enterprise systems, XML serialization supports legacy systems. Conclusion: Shows serializing objects to XML.