JAXBContext实现xml和javabean之间的互相转换

/**
*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());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值