import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; /** * xml和java對象轉換幫助類 * Created by DELL on 2016/5/15. */ public class XmlHelper { /** * 將自定義數據對象轉化為XML字符串 * * @param clazz 自定義數據類型 * @param object 自定義數據對象 * @return XML字符串 * @throws JAXBException 異常 */ public static String objectToXML(Class clazz, Object object) throws JAXBException { String xml = null; JAXBContext context = JAXBContext.newInstance(clazz); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); Writer w = new StringWriter(); m.marshal(object, w); xml = w.toString(); return xml; } /** * 將XML字符串轉化為自定義數據對象 * * @param clazz 自定義數據類型 * @param xml XML字符串 * @return 自定義數據對象 * @throws JAXBException 異常 */ public static Object xmlToObject(Class clazz, String xml) throws JAXBException { JAXBContext context = JAXBContext.newInstance(clazz); Unmarshaller um = context.createUnmarshaller(); return um.unmarshal(new StringReader(xml)); } }