In the previous tutorial, I showed you how to convert an XML file into a Java object using JAXB. This tutorial will guide you to do the opposite, ie converting Java object to XML file using JAXB!
I also have a project as follows:
I will convert the Student object and its properties to an XML file. The Student class must be defined with the annotation of JAXB, specifically as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package com.huongdanjava.jaxb; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Student { private String name; private String age; private String code; public String getName() { return name; } @XmlElement public void setName(String name) { this.name = name; } public String getAge() { return age; } @XmlElement public void setAge(String age) { this.age = age; } public String getCode() { return code; } @XmlElement public void setCode(String code) { this.code = code; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + ", code=" + code + "]"; } } |
OK, now we will define the object Student first:
1 2 3 4 |
Student student = new Student(); student.setName("Khanh"); student.setCode("123456"); student.setAge("30"); |
In the previous tutorial, I introduced to you all the JAXBContext object to create an Unmarshaller object, in addition to this object, we can create another object for our purposes in this tutorial, that is, Marshaller.
1 2 |
JAXBContext jaxbContext = JAXBContext.newInstance(Student.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); |
This Marshaller object provides us with many methods of overloaded marshal() that convert a Java object to an XML file or other output types.
1 2 |
File file = new File("E://student.xml"); jaxbMarshaller.marshal(student, file); |
Result:
If you want to format the XML file, you can use the Marshaller object and add the following code:
1 |
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); |
Rerun the program and we will have the following results:
All codes are as follows, you can refer to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.huongdanjava.jaxb; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Marshaller; import java.io.File; public class JaxbExample { public static void main(String[] args) { try { Student student = new Student(); student.setName("Khanh"); student.setCode("123456"); student.setAge("30"); JAXBContext jaxbContext = JAXBContext.newInstance(Student.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); File file = new File("/Users/Khanh/Desktop/student.xml"); jaxbMarshaller.marshal(student, file); } catch (JAXBException e) { e.printStackTrace(); } } } |