Deserialize XML to Object Example
This program demonstrates deserializing XML into a Java object.
Problem Statement
Write a Java program that deserializes XML into a Student object 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 | } |
| 7 | public class XMLDeserializeExample { |
| 8 | public static void main(String[] args) throws Exception { |
| 9 | System.out.println("Eduinq XML Deserialize Example"); |
| 10 | String xml="<student><id>1</id><name>Arun</name></student>"; |
| 11 | JAXBContext ctx=JAXBContext.newInstance(Student.class); |
| 12 | Unmarshaller u=ctx.createUnmarshaller(); |
| 13 | Student s=(Student)u.unmarshal(new java.io.StringReader(xml)); |
| 14 | System.out.println("Eduinq Student: "+s.id+" "+s.name); |
| 15 | } |
| 16 | } |
Program Output
Eduinq XML Deserialize Example Eduinq Student: 1 Arun
Explanation
Uses JAXB Unmarshaller to convert XML. - Restores object from XML string. - Exception handling ensures safe operations. - In enterprise systems, XML deserialization supports legacy integration. Conclusion: Shows deserializing XML to objects.