1. 程式人生 > >javax.xml + java.io xml和java物件互轉工具類

javax.xml + java.io xml和java物件互轉工具類

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;

/**xml和java物件互轉工具類*@Description:*/
public class JaxbObjectAndXmlUtil {

    public static <T> T 
xml2Object(String xmlStr,Class<T> c) { try { JAXBContext context = JAXBContext.newInstance(c); Unmarshaller unmarshaller = context.createUnmarshaller(); T t = (T) unmarshaller.unmarshal(new StringReader(xmlStr)); return t; } catch
(JAXBException e) { e.printStackTrace(); return null; } } /** * @param object 物件 * @return 返回xmlStr */ public static String object2Xml(Object object) { if(object == null) { return null; } try { StringWriter writer = new
StringWriter(); JAXBContext context = JAXBContext.newInstance(object.getClass()); Marshaller marshal = context.createMarshaller(); marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 格式化輸出 marshal.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// 編碼格式,預設為utf-8 marshal.setProperty(Marshaller.JAXB_FRAGMENT, true);// 是否省略xml頭資訊 marshal.setProperty("jaxb.encoding", "utf-8"); marshal.marshal(object,writer); return new String(writer.getBuffer()); } catch (Exception e) { e.printStackTrace(); return null;} } }