今日筆記系列之Castor

來源:互聯網
上載者:User
筆記
近日對java對象與xml文本的相互轉換有一定興趣,於是乎在網上查看了一下相關的資料。發現了castor。

並瀏覽了該頁面http://www.jdon.com/idea/castor.htm,但發現上面的代碼有一些錯漏。

自己用eclipse寫了一個簡單的代碼如下:(主要參考了上面提到的網站的內容)

該程式是讀入page.xml檔案,然後轉化為java對象。接著把java對象寫到另外一個檔案裡。

****************************************************************************

1.page.xml,要被轉化為對象的頁面

<?xml version="1.0" encoding="UTF-8"?><homepagecollection name="this is sample">   <!-- 對應Homepagecollection類  --> <homepagecontent id="1">   <!-- 對應Homepagecontent 類  -->  <name>About Us</name>  <navlink>1.jsp</navlink>  <icon>images/icon.gif</icon>  <description>An in-depth look at creating applications with XML.</description> </homepagecontent> <homepagecontent id="2">   <!-- 對應Homepagecontent 類  -->  <name>Product|Service</name>  <navlink>2.jsp</navlink>  <icon>images/icon.gif</icon>  <description>let's tak a look at our products.</description> </homepagecontent></homepagecollection>

****************************************************************************

2.Homepagecontent.java,一個符合JavaBean規格的簡單類

package tryForCastor;

public class Homepagecontent implements java.io.Serializable {

    private static final long serialVersionUID = 3689909565688657717L;

    private Integer id;

    private String name;

    private String navlink;        private String icon;

    private String description;

    public Homepagecontent() {    }

    public Integer getId() {        return id;    }

    public void setId(Integer id) {        this.id = id;    }

    public String getName() {        return name;    }

    public void setName(String name) {        this.name = name;    }        public String getNavlink() {        return navlink;    }

    public void setNavlink(String navlink) {        this.navlink = navlink;    }

    public String getIcon() {        return icon;    }

    public void setIcon(String icon) {        this.icon = icon;    }

    public String getDescription() {        return description;    }

    public void setDescription(String description) {        this.description = description;    }

}

****************************************************************************

3.Homepagecollection.java,

package tryForCastor;

import java.util.*;

public class Homepagecollection implements java.io.Serializable {

    private static final long serialVersionUID = 3545239128603309878L;

    private String SiteName;

    private List homepagecontents = new ArrayList();

    public Homepagecollection() {    }

    // -- manipulate the List of Page objects    public void addHomePageContent(Homepagecontent homepagecontent) {        homepagecontents.add(homepagecontent);    }

    public List getHomepagecontents() {        return homepagecontents;    }

    // -- manipulate the name of the address book    public String getName() {        return SiteName;    }

    public void setName(String name) {        this.SiteName = name;    }

}

****************************************************************************

4.mapping.xml,對應檔,把要轉化的xml檔案和java類聯絡起來

<?xml version="1.0" encoding="UTF-8"?><mapping> <description>a map file for our new template system</description> <class name="Homepagecontent">  <map-to xml="homepagecontent"/>  <field name="id" type="integer">   <bind-xml name="id" node="attribute" />  </field>  <field name="name" type="string" />  <field name="navlink" type="string" />  <field name="icon" type="string" />  <field name="description" type="string" /> </class> <class name="Homepagecollection">  <map-to xml="homepagecollection"/>  <field name="name" type="string">   <bind-xml name="name" node="attribute" />  </field>  <field name="homepagecontents" type="Homepagecontent"    collection="collection" /> </class></mapping>

****************************************************************************

5.tryCastor.java,執行轉化的類

package tryForCastor;

import java.io.FileReader;import java.io.FileWriter;import java.util.*;

import org.exolab.castor.mapping.Mapping;import org.exolab.castor.xml.Marshaller;import org.exolab.castor.xml.Unmarshaller;

/** * @author hbm *  */public class tryCastor {    public Mapping mapping;

    public String xmlfile;

    public void HomePageHandle(String mapfile, String xmlfile) throws Exception {        this.xmlfile = xmlfile;        try {            mapping = new Mapping();            mapping.loadMapping(mapfile); //讀入對應檔        } catch (Exception e) {            throw new Exception(e.getMessage());        }

    }

    // -- page.xml中的資料讀入Homepagecollection    public Homepagecollection read() throws Exception {        Homepagecollection homepages = null;        try {            Unmarshaller un = new Unmarshaller(Homepagecollection.class); // xml -> java 專用類            un.setMapping(mapping);

            FileReader in = new FileReader(xmlfile);            homepages = (Homepagecollection) un.unmarshal(in); //轉換            in.close();        } catch (Exception e) {            throw new Exception(e.getMessage());        }        return homepages;    }

    // hbm add    public FileWriter write(String outFile, Object obj) throws Exception {        FileWriter out = new FileWriter(outFile);        try {            Marshaller mar = new Marshaller(out);// java-> xml專用類            mar.setMapping(mapping);            mar.marshal(obj);        } catch (Exception e) {            throw new Exception(e.getMessage());//轉換        }        return out;    }

    /**     * @param args     */    public static void main(String[] args) {        tryCastor tc = new tryCastor();        try {            //從page.xml讀入資料並放到對象hcollection 裡            tc.HomePageHandle("mapping.xml", "page.xml");            Homepagecollection hcollection = tc.read();            List list = hcollection.getHomepagecontents();            for (Iterator iter = list.iterator(); iter.hasNext();) {                Homepagecontent h = (Homepagecontent) iter.next();                System.out.println(h.getDescription());                System.out.println(h.getIcon());                System.out.println(h.getName());                System.out.println(h.getNavlink());                System.out.println(h.getName2());                System.out.println(h.getId());                System.out.println(h.getClass());                System.out.println("+++++++++++++++++++++++");            }                        //寫到xml文本            FileWriter fw = tc.write("d.xml", hcollection);            if (null != fw) {                fw.close();            }

        } catch (Exception e) {            e.printStackTrace();        }

    }

}



****************************************************************************

小結:覺得寫對應檔(mapping.xml)很麻煩,是否可以用映射來解決自動尋找類欄位來實現java到xml的轉換?




相關文章

Beyond APAC's No.1 Cloud

19.6% IaaS Market Share in Asia Pacific - Gartner IT Service report, 2018

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。