Apache Digester应用实例 [转]

Apache Digester应用实例 [转]
前段时间项目中需要根据xml文件创建java对象,而apache commons-digester是首选.
一直想把它写下来,可是总有点懒 这次介绍一下digester的常用法,其他更高级的使用方法请参阅digester doc(由于比较忙,下次有时间写一篇关于cglib的常用法,呵呵)
Apache Digester应用实例 [原创]
--------------利用 apache commons-digester 自动根据xml文件创建java 对象
<day day up>
author: binker
email: [email protected]
date: 2006/12/16
note: 本文可以任意转载,但请保持其完整性并注明来源,谢谢.

一.序
  Digester是apache的一个组件 apache commons-digester.jar,通过它可以很方便的从xml文件生成java对象.你不用再象以前通过jdom或者Xerces去读取一个document对象.(jdom和Xerces仍然有它们的用武之地及强大之处,在其它应用里你也少不了它们)
我只是用一个例子展示一下如何把xml文件生成一个java object.
首先你必须把jar加入到你的项目classpath.
(一)准备:
1.环境: Eclipse, jdk1.4+
2.需求说明:学院包含学生和老师,学生可以选修课程,老师有不同的资格认证。
3.Java Class的定义,简洁起见,略去import内容。
4.使用Digester生成java对象 必须要定义一个xml文件,此xml文件必须符合digester-rules.dtd的规则。
5.所有的xml文件必须在classpath路径中,这样可以通过Class.getClassLoader().getInputStream()读取xml文件。

(二)提要:
  本示例所需的java class 和 xml文件分成四类:
1.基础xml文件: [academy.xml]: 你将要解析的xml文件.
2.基础java class: [Academy.java, Teacher.java, Student.java, Cousre.java]: 生成的对象的类定义
3.digesterRules.xml: [academyRules.xml]: 定义了基础xml文件到基础java class的匹配(映射)关系
4.Digester class: [DigestXMLJavaAcademy.java]: 根据digesterRules.xml去解析基础xml文件,并生成java 对象

(三)参考资料
   1.English ebook: Pro Jakarta Commons by Harshad Oak  Apress 2004

二.基础Java Class
1.学院 class Academy.java
Java代码
  1. public class Academy {  
  2.     private Vector students;  
  3.     private Vector teachers;  
  4.     private String name;  
  5.   
  6.     public Academy() {  
  7.         students = new Vector();  
  8.         teachers = new Vector();  
  9.     }  
  10.   
  11.     public void addStudent(Student student) {  
  12.         students.addElement(student);  
  13.     }  
  14.   
  15.     public void addTeacher(Teacher teacher) {  
  16.         teachers.addElement(teacher);  
  17.     }  
  18.   
  19.     public Vector getStudents() {  
  20.         return students;  
  21.     }  
  22.   
  23.     public void setStudents(Vector newStudents) {  
  24.         students = newStudents;  
  25.     }  
  26.     public Vector getTeachers() {  
  27.         return teachers;  
  28.     }  
  29.   
  30.     public void setTeachers(Vector newTeachers) {  
  31.         teachers = newTeachers;  
  32.     }  
  33.   
  34.     public String getName() {  
  35.         return name;  
  36.     }  
  37.   
  38.     public void setName(String newName) {  
  39.         name = newName;  
  40.     }  
  41. }  
public class Academy {
private Vector students;
private Vector teachers;
private String name;
public Academy() {
students = new Vector();
teachers = new Vector();
}
public void addStudent(Student student) {
students.addElement(student);
}
public void addTeacher(Teacher teacher) {
teachers.addElement(teacher);
}
public Vector getStudents() {
return students;
}
public void setStudents(Vector newStudents) {
students = newStudents;
}
public Vector getTeachers() {
return teachers;
}
public void setTeachers(Vector newTeachers) {
teachers = newTeachers;
}
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
}

============================================================
2.学生 Student.java
Java代码
  1. public class Student {  
  2.     private Vector courses;  
  3.     private String name;  
  4.     private String division;  
  5.   
  6.     public Student() {  
  7.         courses = new Vector();  
  8.     }  
  9.   
  10.     public void addCourse(Course course) {  
  11.         courses.addElement(course);  
  12.     }  
  13.   
  14.     public String getName() {  
  15.         return name;  
  16.     }  
  17.     public void setName(String newName) {  
  18.         name = newName;  
  19.     }  
  20.   
  21.     public String getDivision() {  
  22.         return division;  
  23.     }  
  24.   
  25.     public void setDivision(String newDivision) {  
  26.         division = newDivision;  
  27.     }  
  28.   
  29.     public void setCourses(Vector courses) {  
  30.         this.courses = courses;  
  31.     }  
  32.   
  33.     public Vector getCourses() {  
  34.         return courses;  
  35.     }  
  36. }  
public class Student {
private Vector courses;
private String name;
private String division;
public Student() {
courses = new Vector();
}
public void addCourse(Course course) {
courses.addElement(course);
}
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public String getDivision() {
return division;
}
public void setDivision(String newDivision) {
division = newDivision;
}
public void setCourses(Vector courses) {
this.courses = courses;
}
public Vector getCourses() {
return courses;
}
}

============================================================
3.老师 Teacher.java
Java代码
  1. public class Teacher {  
  2.     private String name;  
  3.     private Vector certifications;  
  4.   
  5.     public Teacher() {  
  6.         certifications = new Vector();  
  7.     }  
  8.   
  9.     public void addCertification(String certification) {  
  10.         certifications.addElement(certification);  
  11.     }  
  12.   
  13.     public String getName() {  
  14.         return name;  
  15.     }  
  16.   
  17.     public void setName(String newName) {  
  18.         name = newName;  
  19.     }  
  20.   
  21.     public void setCertifications(Vector certifications) {  
  22.         this.certifications = certifications;  
  23.     }  
  24.   
  25.     public Vector getCertifications() {  
  26.         return certifications;  
  27.     }  
  28. }  
public class Teacher {
private String name;
private Vector certifications;
public Teacher() {
certifications = new Vector();
}
public void addCertification(String certification) {
certifications.addElement(certification);
}
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public void setCertifications(Vector certifications) {
this.certifications = certifications;
}
public Vector getCertifications() {
return certifications;
}
}

============================================================
4.课程 Course.java
Java代码
  1. public class Course {  
  2.     private String id;  
  3.     private String name;  
  4.   
  5.     public Course() {  
  6.     }  
  7.   
  8.     public String getId() {  
  9.         return id;  
  10.     }  
  11.   
  12.     public void setId(String newId) {  
  13.         id = newId;  
  14.     }  
  15.     public String getName() {  
  16.         return name;  
  17.     }  
  18.   
  19.     public void setName(String newName) {  
  20.         name = newName;  
  21.     }  
  22. }  
public class Course {
private String id;
private String name;
public Course() {
}
public String getId() {
return id;
}
public void setId(String newId) {
id = newId;
}
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
}

三.基础XML文件
============================================================
学院 academy.xml,包含了学生(包含了课程),老师
Java代码
  1. <?xml version="1.0"?>  
  2. <academy name="JAcademy" >  
  3.          <student name="JavaBoy" division="A">  
  4.                   <course>  
  5.                       <id>C1</id>  
  6.                       <name>JSP</name>  
  7.                   </course>  
  8.                   <course>  
  9.                       <id>C2</id>  
  10.                       <name>Servlets</name>  
  11.                   </course>  
  12.          </student>  
  13.          <student name="JavaGirl" division="B">  
  14.                   <course>  
  15.                       <id>C3</id>  
  16.                       <name>EJB</name>  
  17.                   </course>  
  18.          </student>  
  19.   
  20.          <teacher name="JavaGuru">  
  21.                   <certification>SCJP</certification>  
  22.                   <certification>SCWCD</certification>  
  23.          </teacher>  
  24.          <teacher name="JavaMaster">  
  25.                   <certification>OCP</certification>  
  26.                   <certification>SCJP</certification>  
  27.                   <certification>SCEA</certification>  
  28.          </teacher>  
  29. </academy>  
<?xml version="1.0"?>
<academy name="JAcademy" >
<student name="JavaBoy" division="A">
<course>
<id>C1</id>
<name>JSP</name>
</course>
<course>
<id>C2</id>
<name>Servlets</name>
</course>
</student>
<student name="JavaGirl" division="B">
<course>
<id>C3</id>
<name>EJB</name>
</course>
</student>
<teacher name="JavaGuru">
<certification>SCJP</certification>
<certification>SCWCD</certification>
</teacher>
<teacher name="JavaMaster">
<certification>OCP</certification>
<certification>SCJP</certification>
<certification>SCEA</certification>
</teacher>
</academy>

============================================================

四.Digester Class
DigestXMLJavaAcademy.java 和academyRules.xml
其中academyRules.xml用来定义xml文件和java对象的匹配(映射)关系,格式要符合digester-rules.dtd格式约束
DigestXMLJavaAcademy.java 根据academyRules.xml解析academy.xml文件并生成 Academy对象.
============================================================
Java代码
  1. 1. academyRules.xml  
  2. <?xml version="1.0"?>  
  3. <digester-rules>  
  4.   <pattern value="academy">  
  5.       <object-create-rule classname="com.commonsbook.chap7.academy.Academy" />  
  6.      <set-properties-rule />  
  7.      <pattern value="student">  
  8.          <object-create-rule classname="com.commonsbook.chap7.academy.Student" />  
  9.          <set-properties-rule />  
  10.   
  11.          <pattern value="course">  
  12.              <object-create-rule classname="com.commonsbook.chap7.academy.Course" />  
  13.              <bean-property-setter-rule pattern="id"/>  
  14.              <bean-property-setter-rule pattern="name"/>  
  15.              <set-next-rule methodname="addCourse" />  
  16.          </pattern>  
  17.          <set-next-rule methodname="addStudent" />  
  18.      </pattern>  
  19.   
  20.      <pattern value="teacher">  
  21.          <object-create-rule classname="com.commonsbook.chap7.academy.Teacher" />  
  22.          <set-properties-rule />  
  23.          <call-method-rule pattern="certification" methodname="addCertification"  
  24.              paramcount="1" />  
  25.          <call-param-rule pattern="certification" paramnumber="0"/>  
  26.          <set-next-rule methodname="addTeacher" />  
  27.      </pattern>  
  28.  </pattern>  
  29. </digester-rules>  
1. academyRules.xml
<?xml version="1.0"?>
<digester-rules>
<pattern value="academy">
<object-create-rule classname="com.commonsbook.chap7.academy.Academy" />
<set-properties-rule />
<pattern value="student">
<object-create-rule classname="com.commonsbook.chap7.academy.Student" />
<set-properties-rule />
<pattern value="course">
<object-create-rule classname="com.commonsbook.chap7.academy.Course" />
<bean-property-setter-rule pattern="id"/>
<bean-property-setter-rule pattern="name"/>
<set-next-rule methodname="addCourse" />
</pattern>
<set-next-rule methodname="addStudent" />
</pattern>
<pattern value="teacher">
<object-create-rule classname="com.commonsbook.chap7.academy.Teacher" />
<set-properties-rule />
<call-method-rule pattern="certification" methodname="addCertification"
paramcount="1" />
<call-param-rule pattern="certification" paramnumber="0"/>
<set-next-rule methodname="addTeacher" />
</pattern>
</pattern>
</digester-rules>

============================================================
2. DigestXMLJavaAcademy.java
Java代码
  1. public class DigestXMLJavaAcademy {  
  2.     public void digest(){  
  3.         try {  
  4.             //Create Digester using rules defined in academyRules.xml  
  5.             Digester digester = DigesterLoader.createDigester(  
  6.                      this.getClass().getClassLoader().getResource("academyRules.xml"));  
  7.   
  8.             //Parse academy.xml using the Digester to get an instance of Academy  
  9.             Academy a = (Academy)digester.parse(  
  10.             this.getClass().getClassLoader().getResourceAsStream("academy.xml"));  
  11.   
  12.             Vector vStud=a.getStudents();  
  13.             Vector vTeach=a.getTeachers();  
  14.   
  15.             for (int i = 0; i < vStud.size(); i++) {  
  16.                 System.out.println("Student>> "+PropertyUtils.describe(vStud.get(i)));  
  17.             }  
  18.   
  19.             for (int i = 0; i < vTeach.size(); i++) {  
  20.                 System.out.println("Teacher>> "+ PropertyUtils.describe(vTeach.get(i)));  
  21.             }  
  22.          } catch(Exception e) {  
  23.              e.printStackTrace();  
  24.          }  
  25.     }  
  26.   
  27.     public static void main(String[] args) {  
  28.         DigestXMLJavaAcademy xmlDigest= new DigestXMLJavaAcademy();  
  29.         xmlDigest.digest();  
  30.     }  
  31. }  
public class DigestXMLJavaAcademy {
public void digest(){
try {
//Create Digester using rules defined in academyRules.xml
Digester digester = DigesterLoader.createDigester(
this.getClass().getClassLoader().getResource("academyRules.xml"));
//Parse academy.xml using the Digester to get an instance of Academy
Academy a = (Academy)digester.parse(
this.getClass().getClassLoader().getResourceAsStream("academy.xml"));
Vector vStud=a.getStudents();
Vector vTeach=a.getTeachers();
for (int i = 0; i < vStud.size(); i++) {
System.out.println("Student>> "+PropertyUtils.describe(vStud.get(i)));
}
for (int i = 0; i < vTeach.size(); i++) {
System.out.println("Teacher>> "+ PropertyUtils.describe(vTeach.get(i)));
}
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
DigestXMLJavaAcademy xmlDigest= new DigestXMLJavaAcademy();
xmlDigest.digest();
}
}

五.运行结果
自己运行吧,呵呵

六.后记
写下来还真得花点时间呢,不过这也是对自己以前思路的一个整理.
写出来与大家共同分享也是一种乐趣.呵呵.
下次有时间写一篇关于cglib的常用法.

你可能感兴趣的:(Apache Digester应用实例 [转])