JAXB 实现java对象与xml之间互相转换
首先熟悉一下JAXB实现对象与xml互转时常用的一些注解使用:
1.@XmlRootElement,用于类级别的注解,对应xml的跟元素。通过name属性定义这个根节点的名称。
2.@XmlAccessorType,定义映射这个类中的何种类型都需要映射到xml。(如果不存在@XmlAccessorType,默认使用XmlAccessType.PUBLIC_MEMBER注解)
参数:XmlAccessType.FIELD: java对象中的所有成员变量。
XmlAccessType.PROPERTY:java对象中所有通过getter/setter方式访问的成员变量。
XmlAccessType.PUBLIC_MEMBER:java对象中所有的public访问权限的成员变量和通过getter/setter方式访问的成员变量。
XmlAccessType.NONE: java对象的所有属性都不映射为xml的元素。
3.@XmlAttribute,用于把java对象的属性映射为xml的属性,并可通过name属性为生成的xml属性指定别名。
4.@XmlElement,指定一个字段或get/set方法映射到xml的节点。通过name属性定义这个根节点的名称。
5.@XmlElementWrapper,为数组或集合定义一个父节点。通过name属性定义这个父节点的名称。
下面来看一个例子:
先定义一个学生类,Student如下:
1 package com.quest.software.bus4j.ui.framework.extend.frameParase.test; 2 3 import java.util.List; 4 5 import javax.xml.bind.annotation.XmlAttribute; 6 import javax.xml.bind.annotation.XmlElement; 7 import javax.xml.bind.annotation.XmlElementWrapper; 8 9 public class Student { 10 String name; //姓名 11 String sex; //性别 12 int number; //学号 13 String className; //班级 14 List<String> hobby; //爱好 15 16 public Student(){ 17 } 18 public Student(String name,String sex,int number, 19 String className,List<String> hobby) { 20 this.name = name; 21 this.sex = sex; 22 this.number = number; 23 this.className = className; 24 this.hobby = hobby; 25 } 26 @XmlAttribute(name="name") 27 public String getName() { 28 return name; 29 } 30 public void setName(String name) { 31 this.name = name; 32 } 33 34 @XmlAttribute(name="sex") 35 public String getSex() { 36 return sex; 37 } 38 public void setSex(String sex) { 39 this.sex = sex; 40 } 41 42 @XmlAttribute(name="number") 43 public int getNumber() { 44 return number; 45 } 46 public void setNumber(int number) { 47 this.number = number; 48 } 49 50 @XmlElement(name="className") 51 public String getClassName() { 52 return className; 53 } 54 public void setClassName(String className) { 55 this.className = className; 56 } 57 58 @XmlElementWrapper(name="hobbys") 59 @XmlElement(name = "hobby") 60 public List<String> getHobby() { 61 return hobby; 62 } 63 public void setHobby(List<String> hobby) { 64 this.hobby = hobby; 65 } 66 67 }
切记,如果java对象属性同时添加了get和set方法,注解不能定义在属性的定义上,只需在get或者set方法上定义一个即可,否则jaxb会报错!!如下:
Exception in thread "main" com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
Class has two properties of the same name "name"
然后再定义学生集合类,StudentList如下:
1 package com.quest.software.bus4j.ui.framework.extend.frameParase.test; 2 3 import java.util.List; 4 5 import javax.xml.bind.annotation.XmlElement; 6 import javax.xml.bind.annotation.XmlRootElement; 7 8 @XmlRootElement(name="list") 9 public class StudentList { 10 11 List<Student> students; //所有学生信息的集合 12 13 @XmlElement(name = "student") 14 public List<Student> getStudents() { 15 return students; 16 } 17 18 public void setStudents(List<Student> students) { 19 this.students = students; 20 } 21 22 }
最后写xml和java对象互转的类(通过Marshaller类实现将对象转换为xml,同时也可利用Unmarshaller类进行xml转换为类):
1.java对象转换为xml:
1 package com.quest.software.bus4j.ui.framework.extend.frameParase.test; 2 3 import java.io.BufferedWriter; 4 import java.io.File; 5 import java.io.FileWriter; 6 import java.io.IOException; 7 import java.io.StringWriter; 8 import java.util.ArrayList; 9 import java.util.List; 10 11 import javax.xml.bind.JAXBContext; 12 import javax.xml.bind.JAXBException; 13 import javax.xml.bind.Marshaller; 14 15 public class BeanToXml { 16 17 /** 18 * java对象转换为xml文件 19 * @param xmlPath xml文件路径 20 * @param load java对象.Class 21 * @return xml文件的String 22 * @throws JAXBException 23 */ 24 public static String beanToXml(Object obj,Class<?> load) throws JAXBException{ 25 JAXBContext context = JAXBContext.newInstance(load); 26 Marshaller marshaller = context.createMarshaller(); 27 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 28 marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK"); 29 StringWriter writer = new StringWriter(); 30 marshaller.marshal(obj,writer); 31 return writer.toString(); 32 } 33 public static void main(String[] args) throws JAXBException, IOException { 34 List<String> hobby = new ArrayList<>(); 35 hobby.add("篮球"); 36 hobby.add("音乐"); 37 hobby.add("乒乓球"); 38 39 List<Student> studentList = new ArrayList<>(); 40 41 Student st = new Student("张三","男",10001,"尖子班",hobby); 42 studentList.add(st); 43 Student st1 = new Student("李四","男",10002,"普通班",hobby); 44 studentList.add(st1); 45 Student st2 = new Student("莉莉","女",10003,"普通班",hobby); 46 studentList.add(st2); 47 48 StudentList students = new StudentList(); 49 students.setStudents(studentList); 50 String str = BeanToXml.beanToXml(students, StudentList.class); 51 52 //写入到xml文件中 53 String xmlPath = "D:/testConfig.xml"; 54 BufferedWriter bfw = new BufferedWriter(new FileWriter(new File(xmlPath))); 55 bfw.write(str); 56 bfw.close(); 57 } 58 }
测试生成的xml文件如下图:
2.xml转换为java对象:
1 package com.quest.software.bus4j.ui.framework.extend.frameParase.test; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.List; 6 7 import javax.xml.bind.JAXBContext; 8 import javax.xml.bind.JAXBException; 9 import javax.xml.bind.Unmarshaller; 10 11 public class XmlToBean { 12 13 /** 14 * xml文件配置转换为对象 15 * @param xmlPath xml文件路径 16 * @param load java对象.Class 17 * @return java对象 18 * @throws JAXBException 19 * @throws IOException 20 */ 21 public static Object xmlToBean(String xmlPath,Class<?> load) throws JAXBException, IOException{ 22 JAXBContext context = JAXBContext.newInstance(load); 23 Unmarshaller unmarshaller = context.createUnmarshaller(); 24 Object object = unmarshaller.unmarshal(new File(xmlPath)); 25 return object; 26 } 27 28 public static void main(String[] args) throws IOException, JAXBException { 29 String xmlPath = "D:/testConfig.xml"; 30 Object object = XmlToBean.xmlToBean(xmlPath,StudentList.class); 31 StudentList students = (StudentList)object; 32 List<Student> studentList = students.getStudents(); 33 34 for(int i=0;i<studentList.size();i++){ 35 System.out.println(studentList.get(i).name); 36 System.out.println(studentList.get(i).sex); 37 System.out.println(studentList.get(i).number); 38 System.out.println(studentList.get(i).className); 39 for(String str :studentList.get(i).hobby){ 40 System.out.print(str+" "); 41 } 42 System.out.println("-------------"); 43 } 44 } 45 }
测试打印的结果如下:
张三
男
10001
尖子班
篮球 音乐 乒乓球 -------------
李四
男
10002
普通班
篮球 音乐 乒乓球 -------------
莉莉
女
10003
普通班
篮球 音乐 乒乓球 -------------
有不明白的可以联系我,互相交流!
jaxb虽然挺实用,但是在xml转java对象时xml文件不能配置错了,必须严格按照自己定义的java对象的注解来编写xml文件,否则jaxb里面报错很难查错!!!