使用dom4j解析xml标签,将标签属性与文本内容添加进集合

studentInfo.xml



	
		崔卫兵
		PC学院
		62354666
		男,1982年生,硕士,现就读于北京邮电大学
	
	
		张洪泽
		PC学院
		62358888
		男,1987年生,硕士,现就读于中国农业大学
	


映射Student..java

public class Student {
	private String id;
	private String name;
	private String collage;
	private String telephone;
	private String notes;
	private String className;
	private String method;
	public Student(String id, String name, String collage, String telephone,
			String notes, String className, String method) {
		super();
		this.id = id;
		this.name = name;
		this.collage = collage;
		this.telephone = telephone;
		this.notes = notes;
		this.className = className;
		this.method = method;
	}
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCollage() {
		return collage;
	}
	public void setCollage(String collage) {
		this.collage = collage;
	}
	public String getTelephone() {
		return telephone;
	}
	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}
	public String getNotes() {
		return notes;
	}
	public void setNotes(String notes) {
		this.notes = notes;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public String getMethod() {
		return method;
	}
	public void setMethod(String method) {
		this.method = method;
	}
	
}
解析并存入集合:

public class TestStu {
	List list = new ArrayList();

	public static void main(String[] args) throws Exception {
		TestStu t=new TestStu();
		t.loadXML();
	}

	private  void loadXML() throws Exception {
		// TODO Auto-generated method stub
		Document doc = new SAXReader().read(new File("./src/studentInfo.xml"));
		Element root = doc.getRootElement();
		Iterator it1 = root.elementIterator();
		while (it1.hasNext()) {
			Student stu = new Student();
			Element el = it1.next();
			stu.setId(el.attribute("id").getValue());
			stu.setMethod(el.attribute("id").getValue());
			stu.setClassName(el.attribute("id").getValue());
			Iterator it2 = el.elementIterator();
			while (it2.hasNext()) {
				Element el2 = it2.next();
				if ("name".equals(el2.getName())) {
					stu.setName(el2.getTextTrim());
				}
				if ("collage".equals(el2.getName())) {
					stu.setCollage(el2.getTextTrim());
				}
				if ("telephone".equals(el2.getName())) {
					stu.setTelephone(el2.getTextTrim());
				}
				if ("notes".equals(el2.getName())) {
					stu.setNotes(el2.getTextTrim());
				}
			}
			list.add(stu);
		}
		for(Student stu:list)
		{
			System.out.println(stu.getId()+" , "+stu.getName());
		}
	}
}






你可能感兴趣的:(Java)