工具类如下:
import org.springframework.oxm.jaxb.Jaxb2Marshaller; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.HashMap; import java.util.Map; /** * 使用spring Jaxb2Marshaller类 */ public class SpringJAXBUtil { private static final String ENCODING = "UTF-8"; // private static final Log logger = LogFactory.getLog(SpringJAXBUtil.class); public static <T> String ObjectToXml(Object object, Class<T> clazz) { String xml = ""; try { Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); jaxb2Marshaller.setClassesToBeBound(clazz); Map<String, Object> map = new HashMap<>(); map.put("jaxb.formatted.output", true); //格式化输出格式 map.put("jaxb.encoding", "UTF-8"); //设置xml编码 jaxb2Marshaller.setMarshallerProperties(map); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); StreamResult streamResult = new StreamResult(byteArrayOutputStream); jaxb2Marshaller.marshal(object, streamResult); byte[] buf = byteArrayOutputStream.toByteArray(); xml = new String(buf, 0, buf.length, ENCODING); } catch (Exception e) { // logger.error("error when marshalling object to xml string"); e.printStackTrace(); } return xml; } public static <T> Object XmlToObject(String xml, Class<T> clazz) { Object object = null; if (xml != null && !"".equals(xml)) { try { Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller(); jaxb2Marshaller.setClassesToBeBound(clazz); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xml.getBytes(ENCODING)); StreamSource streamSource = new StreamSource(byteArrayInputStream); object = jaxb2Marshaller.unmarshal(streamSource); } catch (Exception e) { // logger.error("error when unmarshalling xml to object string"); e.printStackTrace(); } } return object; } }