/**
*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());
}
JAXBContext实现xml和javabean之间的互相转换
最新推荐文章于 2024-07-05 18:32:10 发布