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>


Digester学习_第1张图片

你可能感兴趣的:(java,apache,tomcat,xml,ejb)