日期:2014-05-16  浏览次数:20542 次

用xml代替数据库的一个小项目--学生管理系统

Student.java

package com.bean;

public class Student {

private String examid;
private String idcard;
private String name;
private String location;
private double grade;
public String getExamid() {
return examid;
}
public void setExamid(String examid) {
this.examid = examid;
}
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
this.grade = grade;
}
}
StudentUtil.java

package com.utils;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.bean.Student;

public class StudentUtil {
private static final String file = "src/student.xml";
// 获得Document文件的方法
public static Document getDocument() {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
return db.parse(file);
} catch (Exception e) {
throw new RuntimeException(e);
}
}

// 写入xml文件的方法
public static void writeXml(Document document) {
try {
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.transform(new DOMSource(document),new StreamResult(new File(file)));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//把节点的值封装到bean中
public static Student nodeBean(Element e,Class<Student> c){
try {
Student s = c.newInstance();
s.setExamid(e.getAttribute("examid"));
s.setIdcard(e.getAttribute("idcard"));
s.setName(e.getElementsByTagName("name").item(0).getTextContent());
s.setLocation(e.getElementsByTagName("location").item(0).getTextContent());
s.setGrade(Double.parseDouble(e.getElementsByTagName("grade").item(0).getTextContent()));
return s;
} catch (Exception e1) {
throw new RuntimeException(e1);
}
}
}
StudentDao.java

package com.dao;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.bean.Student;
import com.utils.StudentUtil;

public class StudentDao {

/**
* @param args
*/
//增加学生
public void insertS(Student s){
Document document = StudentUtil.getDocument();
//创建sutudet节点
Element rootNode = document.createElement("student");
//给sutudet节点设置属性
rootNode.setAttribute("examid",s.getExamid());
rootNode.setAttribute("idcard",s.getIdcard());
//创建sutudet子节点