JAXB là một công nghệ trong J2EE trong lịch sử, rồi sau đó là Java EE, và hiện tại là Jakarta EE. Bài viết giới thiệu các bạn ánh xạ Java object và XML. Việc sử dụng JAXB thường dùng trong thao tác với Java webserivce. Chuẩn bị JDK 7 hoặc JDK 8. Mã nguồn để ở Java language level 7.
File pom.xml
<?xml version="1.0" encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.github.donhuvy</groupId><artifactId>sample_jaxb_java7</artifactId><version>1.0.0</version><name>sample_jaxb_java7</name><url>https://github.com/donhuvy/sample_jaxb_java7</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.7</maven.compiler.source><maven.compiler.target>1.7</maven.compiler.target></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency></dependencies><build><pluginManagement><plugins><plugin><artifactId>maven-clean-plugin</artifactId><version>3.1.0</version></plugin><plugin><artifactId>maven-resources-plugin</artifactId><version>3.0.2</version></plugin><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.8.0</version></plugin><plugin><artifactId>maven-surefire-plugin</artifactId><version>2.22.1</version></plugin><plugin><artifactId>maven-jar-plugin</artifactId><version>3.0.2</version></plugin><plugin><artifactId>maven-install-plugin</artifactId><version>2.5.2</version></plugin><plugin><artifactId>maven-deploy-plugin</artifactId><version>2.8.2</version></plugin><plugin><artifactId>maven-site-plugin</artifactId><version>3.7.1</version></plugin><plugin><artifactId>maven-project-info-reports-plugin</artifactId><version>3.0.0</version></plugin></plugins></pluginManagement></build></project>
Đối tượng Phòng ban, thể hiện qua class Department.java
packageorg.model;importjavax.xml.bind.annotation.XmlAccessType;importjavax.xml.bind.annotation.XmlAccessorType;importjavax.xml.bind.annotation.XmlElement;importjavax.xml.bind.annotation.XmlElementWrapper;importjavax.xml.bind.annotation.XmlRootElement;importjava.util.List;@XmlRootElement(namespace ="http://example.com/jaxb")@XmlAccessorType(XmlAccessType.FIELD)publicclassDepartment{privateString deptNo;privateString deptName;privateString location;@XmlElementWrapper(name ="employees")@XmlElement(name ="employee")privateList<Employee> employees;/**
* This default constructor is required if there are other constructors.
*/publicDepartment(){}publicDepartment(String deptNo,String deptName,String location){this.deptNo = deptNo;this.deptName = deptName;}publicStringgetDeptNo(){return deptNo;}publicvoidsetDeptNo(String deptNo){this.deptNo = deptNo;}publicStringgetDeptName(){return deptName;}publicvoidsetDeptName(String deptName){this.deptName = deptName;}publicStringgetLocation(){return location;}publicvoidsetLocation(String location){this.location = location;}publicList<Employee>getEmployees(){return employees;}publicvoidsetEmployees(List<Employee> employees){this.employees = employees;}}
Đối tượng Nhân viên, thể hiện qua đối tượng Employee.java
packageorg.model;importjavax.xml.bind.annotation.XmlAccessType;importjavax.xml.bind.annotation.XmlAccessorType;importjavax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name ="employee")@XmlAccessorType(XmlAccessType.FIELD)publicclassEmployee{privateString empNo;privateString empName;privateString managerNo;/**
* Must have empty constructor.
*/publicEmployee(){}publicEmployee(String empNo,String empName,String managerNo){this.empNo = empNo;this.empName = empName;this.managerNo = managerNo;}publicStringgetEmpNo(){return empNo;}publicvoidsetEmpNo(String empNo){this.empNo = empNo;}publicStringgetEmpName(){return empName;}publicvoidsetEmpName(String empName){this.empName = empName;}publicStringgetManagerNo(){return managerNo;}publicvoidsetManager(String managerNo){this.managerNo = managerNo;}}
File chạy để xem kết quả App.java
packageorg.example;importorg.model.Department;importorg.model.Employee;importjavax.xml.bind.JAXBContext;importjavax.xml.bind.Marshaller;importjavax.xml.bind.Unmarshaller;importjava.io.File;importjava.io.FileReader;importjava.util.ArrayList;importjava.util.List;/**
* Hello world!
*/publicclassApp{privatestaticfinalString XML_FILE ="departments.xml";publicstaticvoidmain(String[] args){Employee emp1 =newEmployee("20160922","Nguyen Bich Van",null);Employee emp2 =newEmployee("20150724","Nguyen Viet Hung","20160922");Employee emp3 =newEmployee("20140821","Nguyen Tien Nam",null);List<Employee> employees =newArrayList<Employee>();
employees.add(emp1);
employees.add(emp2);
employees.add(emp3);Department department =newDepartment("SALES","ACCOUNTING","HANOI");
department.setEmployees(employees);try{JAXBContext context =JAXBContext.newInstance(Department.class);// Marshalling from Java object to file.Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
marshaller.marshal(department,System.out);File file =newFile(XML_FILE);// Write to file.
marshaller.marshal(department, file);// Write to console screen.System.out.println("Write to file: "+ file.getAbsolutePath());// Unmarshalling from file to console screen.Unmarshaller unmarshaller = context.createUnmarshaller();Department deptFromFile =(Department) unmarshaller.unmarshal(newFileReader(XML_FILE));List<Employee> employeeList = deptFromFile.getEmployees();// Print to console screen.for(Employee employee : employeeList){System.out.println("Employee: "+ employee.getEmpName());}}catch(Exception e){
e.printStackTrace();}}}// Result:// <?xml version="1.0" encoding="UTF-8" standalone="yes"?>// <ns2:department xmlns:ns2="http://example.com/jaxb">// <deptNo>SALES</deptNo>// <deptName>ACCOUNTING</deptName>// <employees>// <employee>// <empNo>20160922</empNo>// <empName>Nguyen Bich Van</empName>// </employee>// <employee>// <empNo>20150724</empNo>// <empName>Nguyen Viet Hung</empName>// <managerNo>20160922</managerNo>// </employee>// <employee>// <empNo>20140821</empNo>// <empName>Nguyen Tien Nam</empName>// </employee>// </employees>// </ns2:department>// Write to file: E:githubsample_jaxb_java7departments.xml// Employee: Nguyen Bich Van// Employee: Nguyen Viet Hung// Employee: Nguyen Tien Nam// Disconnected from the target VM, address: '127.0.0.1:51287', transport: 'socket'//// Process finished with exit code 0
File XML có tên departments.xml
sinh ra sau khi marshalling từ Java object:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><ns2:departmentxmlns:ns2="http://example.com/jaxb"><deptNo>SALES</deptNo><deptName>ACCOUNTING</deptName><employees><employee><empNo>20160922</empNo><empName>Nguyen Bich Van</empName></employee><employee><empNo>20150724</empNo><empName>Nguyen Viet Hung</empName><managerNo>20160922</managerNo></employee><employee><empNo>20140821</empNo><empName>Nguyen Tien Nam</empName></employee></employees></ns2:department>
Nguồn: viblo.asia