public class JaXmlBeanUtil { /** * 将javaBean转换为xml对象 * @param clazz * @param bean * @return */ public static String parseBeanToXml(Class clazz,Object bean){ StringWriter sw = null; try { JAXBContext jaxbContext = JAXBContext.newInstance(clazz); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); sw = new StringWriter(); //该值默认为false,true则不会创建即头信息,即<?xml version="1.0" encoding="UTF-8" standalone="yes"?> jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); jaxbMarshaller.marshal(bean, sw); } catch (JAXBException e) { e.printStackTrace(); } String head = "<?xml version=\"1.0\" encoding=\"GBK\" ?>"; return head+sw.toString(); } /** *将xml对象转换为javaBean * @param clazz * @param xml * @return */ public static Object parseXmlToBean(Class clazz,String xml) throws JAXBException { JAXBContext context = JAXBContext.newInstance(clazz); Unmarshaller unmarshaller = context.createUnmarshaller(); return unmarshaller.unmarshal(new StringReader(xml)); } }
xml与bean互转工具类
最新推荐文章于 2022-06-02 20:59:36 发布