Jakarta-Common-Digester使用笔记
时间:2011-01-28
Digester不是一个XML Parser,它只是对SAX更高层次上的一个封装使用Digester,将XML映射成javaBean. 我们无须了解SAX和DOM的解析过程,只要给Digester添加一些解析规则,就能对一个xml文件进行解析。Digester使用堆栈来保存xml节点(stack.push()方法),当该xml节点中嵌套的所有子节点解析完毕,该节点将被弹出(stack.pup()方法)。Digester最大的优点就是使用模式匹配来表示xml文件中节点之间的父子关系 。
代码如下:
students.xml
<?xml version="1.0" encoding="UTF-8" ?>
<stuClass name="fddfdf">
<student>
<name from="cn">Java Boy</name>
<course>JSP</course>
</student>
<student>
<name>Java Girl</name>
<course>EJB</course>
</student>
</stuClass>
Model类:Student.java
package demo.javabean;
public class Student ...{
private String name;
private String from;
private String course;
public String getName() ...{
return name;
}
public void setName(String name) ...{
this.name = name;
}
public String getFrom() ...{
return from;
}
public void setFrom(String from) ...{
this.from = from;
}
public String getCourse() ...{
return course;
}
public void setCourse(String course) ...{
this.course = course;
}
}
Jakarta-Common-Digester使用笔记(2)
时间:2011-01-28
Model类:StuClass.java
package demo.javabean;
import java.util.Vector;
public class StuClass ...{
private String name;
private Vector students = new Vector();
public String getName() ...{
return name;
}
public void setName(String name) ...{
this.name = name;
}
public Vector getStudents() ...{
return students;
}
public void setStudents(Vector students) ...{
this.students = students;
}
public void addStudent(Student student)...{
students.add(student);
}
}
测试类:DigestStudents.java
package demo;
import java.util.Vector;
import org.apache.commons.digester.Digester;
import demo.javabean.StuClass;
public class DigestStudents ...{
Vector stuClass;
public DigestStudents() ...{
stuClass = new Vector();
}
public static void main(String[] args) ...{
DigestStudents digestStudents = new DigestStudents();
digestStudents.digest();
}
private void digest() ...{
try ...{
Digester digester = new Digester();
// Push the current object onto the stack
digester.setValidating(false);
// Creates a new instance of the Student class
digester.addObjectCreate("stuClass", "demo.javabean.StuClass");
digester.addSetProperties("stuClass", "name", "name");
digester
|