精華區beta java 關於我們 聯絡資訊
[功能] 1. 把 java bean 轉成 xml 2. 把 xml 轉成 java bean [相依的 component] 大致上同 Digester 的相依性,再加上自己 (如果你只做 bean to xml,大概是用不到 Digester) [程序] 1. 產生 BeanWriter/BeanReader BeanWriter beanWriter = new BeanWriter(outputWriter); BeanReader beanReader = new BeanReader(); 2. Configure BeanWriter/BeanReader beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false); beanWriter.getBindingConfiguration().setMapIDs(false); beanWriter.enablePrettyPrint(); beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false); beanReader.getBindingConfiguration().setMapIDs(false); 3. 執行 write 動作 / 執行 read 動作 beanWriter.write("room", new CustomBean()); CustomBean cbean = (CustomBean) beanReader.parse(xmlReader); *. ===================================================.* read 動作之前要先 register bean class beanReader.registerBeanClass("cbean", CustomBean.class); 參數 1 是 root element name *. ===================================================.* 4. xml 建立完成 / java instance 建立完成 ======================================================================||||||| [範例] 俺假設要建立的是房客與客戶的資料,房間有編號與容量,客人有姓名和身份證 字號。房間以 Collection 持有客人的資訊。 import java.util.Collection; /** * Room bean contain room and customs information * @author qrtt1 * */ public class Room { private Collection customs; private Integer number; private Integer capacity; public Room() { } /** * @param number the number of this room * @param capacity how many custom this room can live */ public Room(Integer number, Integer capacity) { assert (number != 0); assert (capacity != 0); this.number = number; this.capacity = capacity; } /** * @param number the number of this room * @param capacity how many custom this room can live * @param customs what are customs having lived in */ public Room(Integer number, Integer capacity, Collection customs) { this(number, capacity); assert (customs != null); this.customs = customs; } /** * @return the capacity of this room */ public Integer getCapacity() { return this.capacity; } /** * @param capacity set capacity for this room */ public void setCapacity(Integer capacity) { this.capacity = capacity; } /** * @return the customs which live in the room */ public Collection getCustoms() { return this.customs; } /** * @param customs set customs which live in the room */ public void setCustoms(Collection customs) { this.customs = customs; } /** * @return the room no. */ public Integer getNumber() { return this.number; } /** * @param number set room no. */ public void setNumber(Integer number) { this.number = number; } /** * @param c add new custom c * @return true if still has space for new custom */ public boolean addCustom(Custom c){ if( customs.size() < capacity){ return this.customs.add(c); } return false; } /** * @param c remove the custom c from this room * @return true if the custom in this room */ public boolean removeCustom(Custom c){ return customs.remove(c); } } /** * Custom bean store the information of a custom * @author qrtt1 * */ public class Custom { private String name; private String id; public Custom(){} /** * @param name custom's name * @param id custom's id */ public Custom(String name, String id) { assert (name != null && (!"".equals(name))); assert (id != null && (!"".equals(id))); this.name = name; this.id = id; } /** * @return custom's id */ public String getId() { return this.id; } /** * @param id custom's id */ public void setId(String id) { this.id = id; } /** * @return custom's name */ public String getName() { return this.name; } /** * @param name custom's name */ public void setName(String name) { this.name = name; } } 接著,為了方便起見,我們建立一個 TestData 類別 import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Collection; import java.util.Vector; public class TestData { /** * @return return out test data */ public static Room getData() { // room no. 103, capacity 8p Room m = new Room(103, 8); Collection<Custom> c = new Vector<Custom>(); c.add(new Custom("qrtt1", "A176537653")); c.add(new Custom("orz", "A2123426543")); c.add(new Custom("xd", "X123456271")); m.setCustoms(c); return m; } public static String getXMLData() { StringBuffer sbuff = new StringBuffer(); String tmp; try { FileReader reader = new FileReader("/home/qrtt1/room.xml"); BufferedReader breader = new BufferedReader(reader); tmp = breader.readLine(); while (tmp != null) { sbuff.append(tmp); tmp = breader.readLine(); } return sbuff.toString(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } } ==============================================================|||||| 讀寫則直接修改手冊裡的範例 import java.io.StringWriter; public class WriteExampleApp { /** * Create an example bean and then convert it to xml. */ public static final void main(String [] args) throws Exception { // Start by preparing the writer // We'll write to a string StringWriter outputWriter = new StringWriter(); // Betwixt just writes out the bean as a fragment // So if we want well-formed xml, we need to add the prolog outputWriter.write("<?xml version='1.0' ?>\n"); // Create a BeanWriter which writes to our prepared stream BeanWriter beanWriter = new BeanWriter(outputWriter); // Configure betwixt // For more details see java docs or later in the main documentation beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false); beanWriter.getBindingConfiguration().setMapIDs(false); beanWriter.enablePrettyPrint(); // If the base element is not passed in, Betwixt will guess // But let's write example bean as base element 'person' //beanWriter.write("person", new PersonBean("John Smith", 21)); beanWriter.write("room", TestData.getData()); // Write to System.out // (We could have used the empty constructor for BeanWriter // but this way is more instructive) System.out.println(outputWriter.toString()); // Betwixt writes fragments not documents so does not automatically close // writers or streams. // This example will do no more writing so close the writer now. outputWriter.close(); } } import java.io.StringWriter; public class WriteExampleApp { /** * Create an example bean and then convert it to xml. */ public static final void main(String [] args) throws Exception { // Start by preparing the writer // We'll write to a string StringWriter outputWriter = new StringWriter(); // Betwixt just writes out the bean as a fragment // So if we want well-formed xml, we need to add the prolog outputWriter.write("<?xml version='1.0' ?>\n"); // Create a BeanWriter which writes to our prepared stream BeanWriter beanWriter = new BeanWriter(outputWriter); // Configure betwixt // For more details see java docs or later in the main documentation beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false); beanWriter.getBindingConfiguration().setMapIDs(false); beanWriter.enablePrettyPrint(); // If the base element is not passed in, Betwixt will guess // But let's write example bean as base element 'person' //beanWriter.write("person", new PersonBean("John Smith", 21)); beanWriter.write("room", TestData.getData()); // Write to System.out // (We could have used the empty constructor for BeanWriter // but this way is more instructive) System.out.println(outputWriter.toString()); // Betwixt writes fragments not documents so does not automatically close // writers or streams. // This example will do no more writing so close the writer now. outputWriter.close(); } } ======================================================================= [心得] 1. 讀與寫的 configure 如果不同的話,會發生讀取的錯誤。 2. 請看倌自行 disable configure -> true 改成 false, false 改成 true 觀察結果。 比較能 make sense 3. 由於 1, 2 的體驗後,你會感到雖然很方便但仍不算實用, 因為 xml 總不是如你預期的樣子, 所以還需要看如何使用客製化設定檔 .betwixt -- 網頁版本 http://www.javaworld.com.tw/jute/post/view?bid=11&id=181066&sty=1&tpg=1&age=0 -- ※ Origin: SayYA 資訊站 <bbs.sayya.org> ◆ From: 163.26.34.20