Apache Commons:Betwixt介绍
http://www.zihou.me/html/2011/03/22/2952.html
Betwixt是Apache Commons家族中又一重要的成員,它可以很容易地將一個XML的內容轉化為一個JavaBean,這一點與Digester倒很相似,但它同時也可以很容易地將一個JavaBean轉化為XML格式的內容。
我們在很多情況下可能都干過這樣的事情,那就是把一些內容輸出為一個XML內容,每次做這樣的工作時是不是覺得特別枯燥沒勁?那你就可以試試Betwixt,讓Betwixt來幫你做這樣的工作,你會發現是如此的輕松容易!
一、官方網址:
http://commons.apache.org/betwixt/ 截至到目前最新版本是0.8。
二、例子
1、 將JavaBean轉為XML內容
代碼如下:
新創建一個Person類
public class PersonBean {
private String name;
private int age;
/** Need to allow bean to be created via reflection */
public PersonBean() {}
public PersonBean(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return “PersonBean[name='" + name + "',age='" + age + "']“;
}
}
?
再創建一個WriteExampleApp類:
import java.io.StringWriter;
import org.apache.commons.betwixt.io.BeanWriter;
public class WriteExampleApp {
/**
* 創建一個例子Bean,并將它轉化為XML.
*/
public static final void main(String [] args) throws Exception {
// 先創建一個StringWriter,我們將把它寫入為一個字符串???????
StringWriter outputWriter = new StringWriter();
// Betwixt在這里僅僅是將Bean寫入為一個片斷
// 所以如果要想完整的XML內容,我們應該寫入頭格式
outputWriter.write(“<?xml version=’1.0′ encoding=’UTF-8′ ?>\n”);
// 創建一個BeanWriter,其將寫入到我們預備的stream中
BeanWriter beanWriter = new BeanWriter(outputWriter);
// 配置betwixt
// 更多詳情請參考java docs 或最新的文檔
beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
beanWriter.getBindingConfiguration().setMapIDs(false);
beanWriter.enablePrettyPrint();
// 如果這個地方不傳入XML的根節點名,Betwixt將自己猜測是什么
// 但是讓我們將例子Bean名作為根節點吧
beanWriter.write(“person”, new PersonBean(“John Smith”, 21));
//輸出結果
System.out.println(outputWriter.toString());
// Betwixt寫的是片斷而不是一個文檔,所以不要自動的關閉掉writers或者streams,
//但這里僅僅是一個例子,不會做更多事情,所以可以關掉
outputWriter.close();
}
}
2、 將XML轉化為JavaBean
import java.io.StringReader;
import org.apache.commons.betwixt.io.BeanReader;
public class ReadExampleApp {
public static final void main(String args[]) throws Exception{
// 先創建一個XML,由于這里僅是作為例子,所以我們硬編碼了一段XML內容
StringReader xmlReader = new StringReader(
“<?xml version=’1.0′ encoding=’UTF-8′ ?> <person><age>25</age><name>James Smith</name></person>”);
//創建BeanReader
BeanReader beanReader? = new BeanReader();
//配置reader
beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
beanReader.getBindingConfiguration().setMapIDs(false);
//注冊beans,以便betwixt知道XML將要被轉化為一個什么Bean
beanReader.registerBeanClass(“person”, PersonBean.class);
//現在我們對XML進行解析
PersonBean person = (PersonBean) beanReader.parse(xmlReader);
//輸出結果
System.out.println(person);
}
}
?
通過上面的例子,是不是覺得非常簡單?當然上面只是簡單的例子,更多的功能應用還需要自己去研究。
?
總結
以上是生活随笔為你收集整理的Apache Commons:Betwixt介绍的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Eclipse使用SVN
- 下一篇: Apache Commons:Commo