studentInfo.xml
<?xml version="1.0" encoding="gbk"?>
<students>
<student id="1" className="xml.UserDao1" method="add">
<name>崔衛兵</name>
<college>PC學院</college>
<telephone>62354666</telephone>
<notes>男,1982年生,碩士,現就讀於北京郵電大學</notes>
</student>
<student id="2" className="xml.UserDao1" method="select">
<name>張洪澤</name>
<college>PC學院</college>
<telephone>62358888</telephone>
<notes>男,1987年生,碩士,現就讀於中國農業大學</notes>
</student>
</students>
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<Student> list = new ArrayList<Student>(); 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<Element> 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<Element> 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()); } } }