环境注明
本文为Java1.7、idea2017
1、创建实体类
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name="School")
@XmlType(propOrder={"schoolName","clazz"})
public class School{
private String schoolName;
private Clazz clazz;
@XmlElement(name="SchoolName")
public String getSchoolName(){
returnschoolName;
}
public void setSchoolName(String schoolName){
this.schoolName=schoolName;
}
@XmlElement(name="Class")
public Clazz getClazz(){
return clazz;
}
public void setClazz(Clazz clazz){
this.clazz=clazz;
}
public static classClazz{
private String clazzName;
private Student student;
@XmlElement(name="ClassName")
public String getClazzName(){
return clazzName;
}
public void setClazzName(String clazzName){
this.clazzName=clazzName;
}
@XmlElement(name="Student")
public Student getStudent(){
return student;
}
public void setStudent(Student student){
this.student=student;
}
}
public static class Student{
private String studentName;
@XmlElement(name="studentName")
public String getStudentName(){
return studentName;
}
public void setStudentName(String studentName){
this.studentName=studentName;
}
}
}
2、创建转换工具方法及测试Main
/**
*xmlString转换成对象
*
*createdbycaizhon2018-05-24v1.0
*/
public static Object convertXmlStrToObject(Classclazz,StringxmlStr)throws Exception{
JAXBContext context=JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller=context.createUnmarshaller();
StringReader sr=new StringReader(xmlStr);
return unmarshaller.unmarshal(sr);
}
/**
*对象转换成xmlString
*
*createdbycaizhon2018-05-24v1.0
*/
public static String convertToXmlStr(Objectobj)throws Exception{
//创建输出流
StringWriter sw=new StringWriter();
//利用jdk中自带的转换类实现
JAXBContext context=JAXBContext.newInstance(obj.getClass());
Marshaller marshaller=context.createMarshaller();
//格式化xml输出的格式
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
//去掉生成xml的默认报文头
//marshaller.setProperty(Marshaller.JAXB_FRAGMENT,Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
//将对象转换成输出流形式的xml
marshaller.marshal(obj,sw);
return sw.toString();
}
public static void main(String[] args) throws Exception{
School school=new School();
school.setSchoolName("武汉工程大学");
School.Clazz clazz=new School.Clazz();
clazz.setClazzName("三年二班");
School.Student student=new School.Student();
student.setStudentName("周杰伦");
clazz.setStudent(student);
school.setClazz(clazz);
String schoolXml= convertToXmlStr(school);
System.out.println(schoolXml);
School school1=(School)convertXmlStrToObject(School.class,schoolXml);
System.out.println(school1.getClazz().getStudent().getStudentName());
}