`

Digester学习

阅读更多

     近来在学习tomcat的源码,其中有个解析XML的工具Digester,感觉很有意思,稍微研究了一下,今天先把写的例子弄上来,以后再讲一下Digester的原理和实现,总体感觉这个组件设计的很巧妙,重点当然是Pattern和Rule已经栈的使用了。

package org.apache.commons.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;

public class DigesterStudents {
	private Vector<Student> students;
	
	public DigesterStudents(){
		students = new Vector<Student>();
	}
	
	public static void main(String[] args){
		DigesterStudents ds = new DigesterStudents();
		ds.digester();
	}
	
	private void digester(){
		Digester digester = new Digester();
		digester.push(this);
		
		digester.addObjectCreate("students/student", Student.class.getName());
		digester.addCallMethod("students/student/name", "setName",1);
		digester.addCallParam("students/student/name", 0);
		digester.addCallMethod("students/student/course", "setCourse",0);
		digester.addSetNext("students/student", "addStudents");
		digester.addSetProperty("students/student/set-name-property", "propertyName", "propertyValue");
		digester.addSetProperty("students/student/set-course-property", "propertyName", "propertyValue");
		
		try {
			InputStream in = this.getClass().getClassLoader()
				.getResourceAsStream("students.xml");
			DigesterStudents ds = (DigesterStudents)digester.parse(in);
			digester.setDebug(10);
			System.out.println(ds.students);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
	}
	
	public void addStudents(Student student){
		students.add(student);
	}
}

package org.apache.commons.test;

public class Student {
	private String name;
	private String course;

	public String getName() {
		return name;
	}

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

	public String getCourse() {
		return course;
	}

	public void setCourse(String course) {
		this.course = course;
	}

	public String toString() {
		return ("Name=" + this.name + " & Course=" + this.course);
	}
}

<?xml version="1.0" ?>
<students>
	<student>
		<name>Java Boy</name>
		<course>JSP</course>
	</student>
	<student>
		<name>Java Girl</name>
		<course>EJB</course>
	</student>  
	<student>
		<set-name-property propertyName="name" propertyValue="Java Hobbies" />
		<set-course-property propertyName="course" propertyValue="Java Programming" />
	</student>
</students>


  • 大小: 44.8 KB
分享到:
评论
2 楼 asialee 2011-12-01  
cuitzyj 写道
jaxb直接搞定,比这个简单。 我也在tomcat源码,看到这个类时比较费解,不清楚它是如何做到的,thxs

这个我看过了Digester的源码,欢迎交流,还是比较简单的。
1 楼 cuitzyj 2011-11-30  
jaxb直接搞定,比这个简单。 我也在tomcat源码,看到这个类时比较费解,不清楚它是如何做到的,thxs

相关推荐

Global site tag (gtag.js) - Google Analytics