Digester原是Apache Jakarta Struts计划中的一部分,用来解析Web App中的XML配置文件,在开发一段时间之后,开发人员觉得这个小工具具有很普遍的使用场合,于是,将这个部分独立出来,放到Commons项目中。
Digester是一个将配置文件转换为Java对象的工具,有三个核心概念:
①:元素匹配规则Pattern(有点类似于XPath) →找出XML配置文件中对应的部分准备处理
②:处理规则Rule; →指定一个处理规则来处理这些待处理的元素
③:对象栈 →按照解析的层次关系,将XML配置文件中解析出的对象依次入栈
Digester解析的步骤:
①:创建一个Digester类的实例;
②:指定其使用的Pattern及Rule;
③:传递一个引用XML文件的对象参数到parse()方法;
try {
File input = new File(args[0]);
File rules = new File(args[1]);
//创建digester对象并指定解析规则
Digester digester = DigesterLoader.createDigester(rules.toURL());
//传递配置文件引用input到digester进行解析,解析出的对象就是对应的对象;
Catalog catalog = (Catalog) digester.parse(input);
System.out.println(catalog.toString());
} catch (Exception exc) {
exc.printStackTrace();
}
配置文件input如下:
<?xml version="1.0"?>
<!-- edited with XMLSPY v2004 rel. 2 U (http://www.xmlspy.com) by Leo (SinoBestStar) -->
<catalog library="somewhere">
<book>
<author>Author 1</author>
<title>Title 1</title>
</book>
<book>
<author>Author 2</author>
<title>His One Book</title>
</book>
<magazine>
<name>Mag Title 1</name>
<article page="5">
<headline>Some Headline</headline>
</article>
<article page="Array">
<headline>Another Headline</headline>
</article>
</magazine>
<book>
<author>Author 2</author>
<title>His Other Book</title>
</book>
<magazine>
<name>Mag Title 2</name>
<article page="17">
<headline>Second Headline</headline>
</article>
</magazine>
</catalog>
Pattern规则文件如下:
<?xml version="1.0"?>
<digester-rules>
<object-create-rule pattern="catalog" classname="Catalog"/>
<set-properties-rule pattern="catalog">
<alias attr-name="library" prop-name="library"/>
</set-properties-rule>
<pattern value="catalog/book">
<object-create-rule classname="Book"/>
<call-method-rule pattern="author" methodname="setAuthor" paramcount="0"/>
<call-method-rule pattern="title" methodname="setTitle" paramcount="0"/>
<set-next-rule methodname="addBook"/>
</pattern>
<pattern value="catalog/magazine">
<object-create-rule classname="Magazine"/>
<call-method-rule pattern="name" methodname="setName" paramcount="0"/>
<pattern value="article">
<object-create-rule classname="Article"/>
<set-properties-rule>
<alias attr-name="page" prop-name="page"/>
</set-properties-rule>
<call-method-rule pattern="headline" methodname="setHeadline" paramcount="0"/>
<set-next-rule methodname="addArticle"/>
</pattern>
<set-next-rule methodname="addMagazine"/>
</pattern>
</digester-rules>
本文介绍Apache Commons Digester工具,用于将XML配置文件转换为Java对象。文章详细解释了Digester的工作原理,包括Pattern、Rule及对象栈的概念,并通过示例展示了如何使用Digester进行配置文件的解析。

被折叠的 条评论
为什么被折叠?



