JAXB实现对象与xml互转
import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.StringReader; import java.nio.charset.StandardCharsets; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; public class XmlUtil { /** * JAVA对象转xml * @param object java对象 * @param <T> * @return xml字符串 * @throws JAXBException */ public static <T> String convertXml(T object) throws JAXBException { JAXBContext context = JAXBContext.newInstance(object.getClass()); // 创建 Marshaller装配器实例 Marshaller marshaller = context.createMarshaller(); // 可以设置的属性参见方法:com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.setProperty() marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name()); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); // 指定xml文件头 marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // 将xml写入流中 marshaller.marshal(object, outputStream); // 将流转换成字符串 return new String(outputStream.toByteArray(), StandardCharsets.UTF_8); } /** * xml报文转java对象 * @param xml xml报文 * @param clazz java对象类 * @param <E> * @return java对象 * @throws JAXBException */ public static <E> E convertObject(String xml, Class<E> clazz) throws JAXBException { JAXBContext context = JAXBContext.newInstance(clazz); // 创建unmarshaller解组器实例 Unmarshaller unmarshaller = context.createUnmarshaller(); StringReader stringReader = new StringReader(xml); return (E) unmarshaller.unmarshal(stringReader); } /** * xml文件流转java对象 * @param inputStream xml文件流 * @param clazz java对象类型 * @param <E> * @return java对象 * @throws JAXBException */ public static <E> E convertObject(InputStream inputStream, Class<E> clazz) throws JAXBException { JAXBContext context = JAXBContext.newInstance(clazz); // 创建unmarshaller解组器实例 Unmarshaller unmarshaller = context.createUnmarshaller(); return (E) unmarshaller.unmarshal(inputStream); } }