package org.jeecg.modules.iot.util; import lombok.extern.slf4j.Slf4j; import javax.xml.bind.*; import java.io.*; /** * JAXB工具类 * * @author cuikaidong * 2024年12月20日 */ @Slf4j public class JaxbUtil { private static JAXBContext jaxbContext; //xml转java对象 public static Object xmlToBean(String str, Class load) { Object object = null; try { File file = new File(str); JAXBContext jaxbContext = JAXBContext.newInstance(load); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); object = unmarshaller.unmarshal(file); } catch (JAXBException e) { log.error("xml转换到实体时出错,xml信息={},报错信息={}!", str, e); } return object; } //java对象转xml public static String beanToXml(Object obj) { StringWriter writer = null; try { jaxbContext = JAXBContext.newInstance(obj.getClass()); Marshaller marshaller = jaxbContext.createMarshaller(); //Marshaller.JAXB_FRAGMENT:是否省略xml头信息,true省略,false不省略 marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); //Marshaller.JAXB_FORMATTED_OUTPUT:决定是否在转换成xml时同时进行格式化(即按标签自动换行,否则即是一行的xml) marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //Marshaller.JAXB_ENCODING:xml的编码方式 marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); writer = new StringWriter(); marshaller.marshal(obj, writer); } catch (JAXBException e) { log.info(e.getMessage()); } return "\n" + writer.toString(); } }