利用dom4j包和反射动态解析不同实体类型的xml文件

自己写了个根据传入的实体类能够动态的解析相应的Xml文件的工具类

xml文件结构如下 

TeacherTable:
<TeacherTable>
 <Table1>
    <DepartmentID>30</DepartmentID>
    <BMH>214</BMH>
    <DepartmentName>外国语学院</DepartmentName>
    <TeacherNO>P284</TeacherNO>
    <TeacherName>张三丰</TeacherName>
    <IdentityNO>42050288885198888</IdentityNO>
    <Degree>无</Degree>
    <Rank />
    <Resume />
    <Email />
  </Table1>
</TeacherTable>

StudentTable
<StudentTable> 
 <Table1>
    <DepartmentID>59</DepartmentID>
    <DepartmentName>物理学院</DepartmentName>
    <StuID>999999</StuID>
    <ClassNO>20109999</ClassNO>
    <StuNO>2010999999</StuNO>
    <StuName>李小四</StuName>
    <Grade>2010</Grade>
    <Sex>男</Sex>
    <Birthday>19900101</Birthday>
    <PoliticalState>共青团员</PoliticalState>
    <SpecialName>物理</SpecialName>
    <SpecialID>279</SpecialID>
    <Nation>汉族</Nation>
    <IdentityNO>42099199109279999</IdentityNO>
    <EduYear>4</EduYear>
    <EduLever>本科</EduLever>
  </Table1>
</StudentTable>

相应的实体类

package net.model;

/**
 * 老师信息格式
 */
public class TeacherTable {
	private String DepartmentID;
	private String BMH;
	private String DepartmentName;
	private String TeacherNO;
	private String TeacherName;
	private String IdentityNO;
	private String Degree;
	private String Rank;
	private String Resume;
	private String Email;
	public String getDepartmentID() {
		return DepartmentID;
	}
	public void setDepartmentID(String departmentID) {
		DepartmentID = departmentID;
	}
	public String getBMH() {
		return BMH;
	}
	public void setBMH(String bMH) {
		BMH = bMH;
	}
	public String getDepartmentName() {
		return DepartmentName;
	}
	public void setDepartmentName(String departmentName) {
		DepartmentName = departmentName;
	}
	public String getTeacherNO() {
		return TeacherNO;
	}
	public void setTeacherNO(String teacherNO) {
		TeacherNO = teacherNO;
	}
	public String getTeacherName() {
		return TeacherName;
	}
	public void setTeacherName(String teacherName) {
		TeacherName = teacherName;
	}
	public String getIdentityNO() {
		return IdentityNO;
	}
	public void setIdentityNO(String identityNO) {
		IdentityNO = identityNO;
	}
	public String getDegree() {
		return Degree;
	}
	public void setDegree(String degree) {
		Degree = degree;
	}
	public String getRank() {
		return Rank;
	}
	public void setRank(String rank) {
		Rank = rank;
	}
	public String getResume() {
		return Resume;
	}
	public void setResume(String resume) {
		Resume = resume;
	}
	public String getEmail() {
		return Email;
	}
	public void setEmail(String email) {
		Email = email;
	}
}
package net.model;

/**
 * 学生信息格式
 */
public class StudentTable {
	 private String DepartmentID;
	 private String DepartmentName;
	 private String StuID;
	 private String ClassNO;
	 private String StuNO;
	 private String StuName;
	 private String Grade;
	 private String Sex;
	 private String Birthday;
	 private String PoliticalState;
	 private String SpecialName;
	 private String SpecialID;
	 private String Nation;
	 private String IdentityNO;
	 private String EduYear;
	 private String EduLever;
	 public String getDepartmentID() {
		return DepartmentID;
	}
	public void setDepartmentID(String departmentID) {
		DepartmentID = departmentID;
	}
	public String getDepartmentName() {
		return DepartmentName;
	}
	public void setDepartmentName(String departmentName) {
		DepartmentName = departmentName;
	}
	public String getStuID() {
		return StuID;
	}
	public void setStuID(String stuID) {
		StuID = stuID;
	}
	public String getClassNO() {
		return ClassNO;
	}
	public void setClassNO(String classNO) {
		ClassNO = classNO;
	}
	public String getStuNO() {
		return StuNO;
	}
	public void setStuNO(String stuNO) {
		StuNO = stuNO;
	}
	public String getStuName() {
		return StuName;
	}
	public void setStuName(String stuName) {
		StuName = stuName;
	}
	public String getGrade() {
		return Grade;
	}
	public void setGrade(String grade) {
		Grade = grade;
	}
	public String getSex() {
		return Sex;
	}
	public void setSex(String sex) {
		Sex = sex;
	}
	public String getBirthday() {
		return Birthday;
	}
	public void setBirthday(String birthday) {
		Birthday = birthday;
	}
	public String getPoliticalState() {
		return PoliticalState;
	}
	public void setPoliticalState(String politicalState) {
		PoliticalState = politicalState;
	}
	public String getSpecialName() {
		return SpecialName;
	}
	public void setSpecialName(String specialName) {
		SpecialName = specialName;
	}
	public String getSpecialID() {
		return SpecialID;
	}
	public void setSpecialID(String specialID) {
		SpecialID = specialID;
	}
	public String getNation() {
		return Nation;
	}
	public void setNation(String nation) {
		Nation = nation;
	}
	public String getIdentityNO() {
		return IdentityNO;
	}
	public void setIdentityNO(String identityNO) {
		IdentityNO = identityNO;
	}
	public String getEduYear() {
		return EduYear;
	}
	public void setEduYear(String eduYear) {
		EduYear = eduYear;
	}
	
}

开始写一个Xml解析工具类

package net.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.tudentTable;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XMLUtil {

	@SuppressWarnings("unchecked")
	public static List toModuleList(InputStream input, String className) {
		SAXReader reader = new SAXReader();
		reader.setValidation(false);
		Document document = null;
		List list = new ArrayList();
		try {
			// 解析xml
			document = reader.read(input);
			// 根节点
			Element root = document.getRootElement();
			Iterator it = root.elementIterator();
			// 次节点循环
			while (it.hasNext()) {
                               // 次子节点
				Element nodeFirst = (Element) it.next();
                                //反射
                                Class objCls = Class.forName(className);
				Object obj = objCls.newInstance();
				// 获得传入实体类的所有方法
				Method[] methods = objCls.getMethods();
				for (Method getter : methods) {
					String name = getter.getName();
					Method setter = null;
					// 获取get方法,
					if (name.startsWith("get")) {
						//相应的set方法名
						String lastName = name.substring(3);
						String setName = "set" + lastName;
						//get方法返回数据的类型
						Class type = getter.getReturnType();
						try {
                                                //相应的set方法
						setter = objCls.getMethod(setName, type);
						} catch (NoSuchMethodException e) {
							continue;
						}
                                                //根据节点名获得相应的内容
					        String val = nodeFirst.elementText(lastName);
						//调用set方法
						setter.invoke(obj, val);
					}
				}
				list.add(obj);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("xml文件读取错误", e);
		}
		return list;
	}

	public static void main(String[] args) throws FileNotFoundException {
		InputStream input = new FileInputStream(
				"studentTable.xml");
		List list = XMLUtil.toModuleList(input,
				"net.model.StudentTable");
		for (int i = 0; i < list.size(); i++) {
			StudentTable stuTable = (StudentTable) list.get(i);
			if (stuTable != null) {
				System.out.println("test" + stuTable.getStuName());
				System.out.println("test" + stuTable.getStuNO());
			}
		}
               input.close();

	}

}

其实需要同步的数据是别人提供的接口返回来的String类型的数据。用Xml模拟完之后,开始想的是先把获得的数据生成Xml,再读取xml来解析。后来才发现dom4j可以直接解析String类型的,现在知道的有两种方法

1.保留SAXReader 

Document document = new SAXReader().read(new StringReader(传入的字符串));

2.可以直接省去SAXReader

Document document = DocumentHelper.parseText(传入的字符串);

实体类的属性名称开头是大写,这样命名貌似不规范,但是没法了,写的时候是直接复制过来。

哈哈,现在还是菜鸟,其实如果不怕麻烦一个文件写一个解析方法是就行了; 但是,正因为菜所以才想着做成动态的解析的方式,好让自己学习巩固反射机制,这个自己用的太少了。

有什么错误还请指正~~~

相关推荐