xml_TO_object

一般对于开发人员拿到的xml文件都是配置文件,所以对于我们来说,最主要要做的事情是将xml的内容封装成对象。

下面展示代码

package javaDom4j;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader; class student {
private String id;
private String Snumber;
private String name;
private String className;
private String sex;
private String level;
private String contactMethod;
// private String skill;
private String codeLanguage;
private String career;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSnumber() {
return Snumber;
}
public void setSnumber(String snumber) {
Snumber = snumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getContactMethod() {
return contactMethod;
}
public void setContactMethod(String contactMethod) {
this.contactMethod = contactMethod;
}
// public String getSkill() {
// return skill;
// }
// public void setSkill(String skill) {
// this.skill = skill;
// }
public String getCodeLanguage() {
return codeLanguage;
}
public void setCodeLanguage(String codeLanguage) {
this.codeLanguage = codeLanguage;
}
public String getCareer() {
return career;
}
public void setCareer(String career) {
this.career = career;
}
@Override
public String toString() {
return "student [id=" + id + ", Snumber=" + Snumber + ", name=" + name
+ ", className=" + className + ", sex=" + sex + ", level="
+ level + ", contactMethod=" + contactMethod
+ ", codeLanguage=" + codeLanguage + ", career=" + career + "]";
} } public class xml_To_object {
public static void main(String[] args) throws Exception {
SAXReader reader = new SAXReader();
Document doc = reader.read("Students.xml");
List<student> students = new ArrayList<student>(); //读取student标签
Iterator<Element> iterator = doc.getRootElement().elementIterator("student");
while(iterator.hasNext()) {
Element e = iterator.next();
student stu = new student(); stu.setId(e.attributeValue("id"));
stu.setName(e.elementText("name"));
stu.setClassName(e.elementText("class"));
stu.setSex(e.elementText("sex"));
stu.setLevel(e.elementText("level"));
stu.setContactMethod(e.elementText("contactMethod"));
stu.setCodeLanguage(e.element("skill").elementText("codeLanguage"));
stu.setCareer(e.element("skill").elementText("career")); students.add(stu); } for (student student : students) {
System.out.println(student);
}
} }
上一篇:jQuery选择器总结


下一篇:[Spark][Python]Wordcount 例子