1 什么是 common digester
jakarta common digester 是一套 xml to object 的 api,它可以将xml文件转换为任意的java对象,并且提供灵活的扩展接口。
2 原理
2.1 简单的例子
将以下 xml 文件构造成 arraylist;
<?xml version="1.0" encoding="iso8859_1"?>
<list>
<bean id="1111" description="abc"/>
<bean id="2222" description="bcd"/>
</list>
bean 类
public class bean
{
private string id;
private string description;
public void setid(string id)
{
this.id = id;
}
public string getid()
{
return id;
}
public void setdescription(string description)
{
this.description = description;
}
public string getdescription()
{
return description;
}
}
digester digester = new digester();
digester.addobjectcreate("list", arraylist.class):
digester.addobjectcreate("list/bean" bean.class);
digester.addsetproperties("list/bean");
digester.addsetnext("list/bean", "add");
/*todo: load xml file as stream*/
inputstream is = null;
arraylist list = (arraylist) digester.parse(is);
2.2 digester 的处理过程 (rule, xpath, object stack)
首先为 digester 指明处理规则, 每种处理规则都要匹配 xpath,如下:
digester.addobjectcreate("list", arraylist.class):
digester.addobjectcreate("list/bean" bean.class);
digester.addsetproperties("list/bean");
digester.addsetnext("list/bean", "add");
注意:上述程序并不是处理 xml 文档,而且指明如何处理 xml 文档
然后,digester 开始解析 xml 文档
digester.parse(is);
digester 遍历整个 dom 树, 当遇到一个元素时,便找到与该元素路径匹配的 rule,并调用这个 rule 来处理该元素。
rule 使用 digester 的 object stack 来使用或存放中间处理过程产生的对象。当整棵数遍历完毕时,object stack
栈底的对象即为最后结果对象。
2.3 使用 digester 内建的规则
objectcreate
setnext
setproperties
setproperty
callmethod
factorycreate
2.4 使用自定义的规则
对于第一个例子,不使用内建的规则,而使用自定的规则处理,用于演示自定义规则的用法
public class listrule
extends rule
{
public void begin(string namespace, string name, attributes attributes) throws exception
{
/*将一个新的 arraylist 对象放入 object stack 中*/
digester.push(new arraylist());
}
}
public class beanrule
extends rule
{
public void begin(string namespace, string name, attributes attributes) throws exception
{
/*取出栈顶的对象,当处理该规则时,栈顶应该是 arraylist*/
arraylist list = (arraylist) digester.peek();
bean bean = new bean();
bean.setid(attributes.getvalue("id"));
bean.setdescription(attributes.getvalue("description"));
list.add(bean);
}
}
digester digester = new digester();
digester.addrule("list", new listrule()):
digester.addrule("list/bean" new beanrule());
/*todo: load xml file as stream*/
inputstream is = null;
arraylist list = (arraylist) digester.parse(is);
闽公网安备 35060202000074号