1. 程式人生 > >XML轉Bean

XML轉Bean

attr ring nth ati catch gets javabean IE tex

XML轉Bean有很多方式,我使用的是xtream方式實現xml與bean的互轉。

下面是簡單的xml轉bean

    /**
     * XML轉換成bean
     * @param obj
     * @return yuyuchen
     */
    public static Object XmlTojavaBean(String xmlOut) {
        Object object = null;         
        try {
            Class<?> cl = Class.forName(xmlOut);
            XStream xStreamOut 
= new XStream(new DomDriver()); xStreamOut.processAnnotations(cl); object = xStreamOut.fromXML(xmlOut); } catch (ClassNotFoundException e) { e.printStackTrace(); } return object; }

下面是需要特殊化處理一些別名,去掉class等

/**
     * XML轉換成bean
     * 
@param obj * @return yuyuchen * @throws DocumentException */ public static IEsbServBodyResponse XmlTojavaBeanResp(Class<?> bean,String xmlIn) throws ClassNotFoundException, DocumentException { XStream xStreamIn = new XStream(new DomDriver()); Class<?> clx = bean;
// 處理註解 xStreamIn.processAnnotations(clx); // 標簽“name”, 解析為clx類 xStreamIn.alias(clx.getSimpleName().toLowerCase(), clx); // 設置標簽class屬性,為null(組裝xml需要用到) xStreamIn.aliasSystemAttribute(null, "class"); xStreamIn.addDefaultImplementation(bean, IEsbServBodyResponse.class);//此處可以轉為泛型以適配所有類 // 忽略未知的元素 xStreamIn.ignoreUnknownElements(); Document document = DocumentHelper.parseText(xmlIn); xmlIn = document.getRootElement().asXML(); return (IEsbServBodyResponse) xStreamIn.fromXML(xmlIn); }

bean轉xml:

    /**
     * bean轉換成XML
     * @param obj
     * @return yuyuchen
     */
    public static String javaBeanToXml(Object obj) {
        XStream xstream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_")));//別名中如有橫杠‘-’或下劃線‘_’,xstram會自動轉2個下劃線,該方法是轉為一個下劃線
        xstream.aliasSystemAttribute(null, "class");
        xstream.autodetectAnnotations(true);//開啟自動註解
        String xmlstr = xstream.toXML(obj);
        return xmlstr;
    }

XML轉Bean