一: 需求描述
学生成绩管理系统,使用xml存储学生信息,可以对学生信息进行增、删、删除操作。
主要目的:练习操作xml元素的增删改查
二:代码结构
1:xml存储数据如下
exam.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<students>
<student>
<name sid="111">李四</name>
<age>23</age>
<gender>男</gender>
</student>
<student>
<name sid="222">张三</name>
<age>21</age>
<gender>女</gender>
</student>
</students>
2:Student类封装学生信息
/**
*
*/
package com.hlcui.entity; /**
* @author Administrator
*
*/
public class Student {
private int id;
private String name;
private int age;
private String gender; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getGender() {
return gender;
} public void setGender(String gender) {
this.gender = gender;
} }
3:数据访问层,封装操作xml数据的方法
/**
*
*/
package com.hlcui.dao; import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList; import com.hlcui.entity.Student;
import com.hlcui.exception.NameNotFoundException;
import com.hlcui.utils.StudentUtils; /**
* @author Administrator
*
*/
public class StudentDAO {
// 添加学生信息
public void add(Student stu) {
try {
Document doc = StudentUtils.getDocument();
Element student = doc.createElement("student");
student.setAttribute("id", stu.getId() + ""); // 给学生元素添加属性 // 分别创建姓名、年龄、性别节点
Element name = doc.createElement("name");
name.setTextContent(stu.getName());
Element age = doc.createElement("age");
age.setTextContent(stu.getAge() + "");
Element gender = doc.createElement("gender");
gender.setTextContent(stu.getGender()); // 将姓名、年龄、性别节点添加到学生节点上
student.appendChild(name);
student.appendChild(age);
student.appendChild(gender); // 在将student节点添加到students节点上
doc.getElementsByTagName("students").item(0).appendChild(student);
StudentUtils.write2XML(doc);
System.out.println("添加成功!");
} catch (Exception e) {
e.printStackTrace();
}
} // 根据学生姓名查询学生信息
public Student find(String name) throws NameNotFoundException {
try {
Document doc = StudentUtils.getDocument();
NodeList list = doc.getElementsByTagName("student");
for (int i = 0; i < list.getLength(); i++) {
Element ele = (Element) list.item(i);
if (name.equals((ele.getElementsByTagName("name")).item(0)
.getTextContent())) {
Student stu = new Student();
stu.setId(Integer.parseInt(ele.getAttribute("id")));
stu.setName(name);
stu.setAge(Integer.parseInt((ele
.getElementsByTagName("age")).item(0)
.getTextContent()));
stu.setGender(ele.getElementsByTagName("gender").item(0)
.getTextContent());
return stu;
}
}
throw new NameNotFoundException(name + "不存在!!!");
} catch (NameNotFoundException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} // 根据id删除学生信息
public boolean delete(int id) {
try {
Document doc = StudentUtils.getDocument();
NodeList list = doc.getElementsByTagName("student");
for (int i = 0; i < list.getLength(); i++) {
Element ele = (Element) list.item(i);
if (String.valueOf(id).equals(ele.getAttribute("id"))) {
ele.getParentNode().removeChild(ele);
StudentUtils.write2XML(doc);
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
4:自定义异常类,封装异常
/**
*
*/
package com.hlcui.exception; /**
* @author Administrator
*
*/
public class NameNotFoundException extends Exception { /**
*
*/
private static final long serialVersionUID = 1L; /**
*
*/
public NameNotFoundException() {
} /**
* @param message
*/
public NameNotFoundException(String message) {
super(message);
} /**
* @param cause
*/
public NameNotFoundException(Throwable cause) {
super(cause);
} /**
* @param message
* @param cause
*/
public NameNotFoundException(String message, Throwable cause) {
super(message, cause);
} }
5:junit框架测试DAO方法
/**
*
*/
package com.hlcui.test; import org.junit.Test; import com.hlcui.dao.StudentDAO;
import com.hlcui.entity.Student;
import com.hlcui.exception.NameNotFoundException; /**
* @author Administrator
*
*/
public class TestStudentDAO {
private StudentDAO dao = new StudentDAO(); @Test
public void testAdd() {
Student stu = new Student();
stu.setId(333);
stu.setName("王二");
stu.setAge(27);
stu.setGender("男");
dao.add(stu);
} @Test
public void testFind() throws NameNotFoundException {
String name = "王二";
Student stu = dao.find(name);
System.out.println("学号:" + stu.getId() + "\n姓名:" + stu.getName()
+ "\n年龄:" + stu.getAge() + "\n性别:" + stu.getGender()); } @Test
public void testDelete() {
int id = 333;
boolean flag = dao.delete(id);
System.out.println(flag ? "删除成功!!" : "删除失败!!");
}
}
6:封装操作dom文件功能方法
/**
*
*/
package com.hlcui.utils; import java.io.FileOutputStream;
import java.io.IOException; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; /**
* @author Administrator
*
*/
public class StudentUtils { /* 获取Document对象* */
public static Document getDocument() throws Exception {
DocumentBuilderFactory sfb = DocumentBuilderFactory.newInstance();
DocumentBuilder db = sfb.newDocumentBuilder();
Document doc = db.parse("xml/exam.xml");
return doc;
} /* 将内存中的内容写到硬盘* */
public static void write2XML(Document doc) throws Exception {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer tf = factory.newTransformer();
tf.transform(new DOMSource(doc), new StreamResult(new FileOutputStream(
"xml/exam.xml")));
}
}
7:用户交互界面
/**
*
*/
package com.hlcui.ui; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; import com.hlcui.dao.StudentDAO;
import com.hlcui.entity.Student;
import com.hlcui.exception.NameNotFoundException; /**
* @author Administrator 用户交互界面
*/
public class Main { public static StudentDAO dao = new StudentDAO(); /**
*
* @param args
*/
public static void main(String[] args) { System.out.println("请选择操作模式:a:添加用户 b:查找用户 c:删除用户 exit:退出系统");
BufferedReader br = null;
try {
while (true) {
br = new BufferedReader(new InputStreamReader(System.in));
String type = br.readLine();
if ("a".equals(type)) { // 录入数据
System.out.println("请输入学号:");
int id = Integer.parseInt(br.readLine());
System.out.println("请输入姓名:");
String name = br.readLine();
System.out.println("请输入年龄:");
int age = Integer.parseInt(br.readLine());
System.out.println("请输入性别:");
String gender = br.readLine();
// 封装数据
Student stu = new Student();
stu.setId(id);
stu.setName(name);
stu.setAge(age);
stu.setGender(gender); // 插入数据
dao.add(stu);
} else if ("b".equals(type)) {
System.out.println("请输入姓名:");
String name = br.readLine();
try {
Student stu = dao.find(name);
System.out.println("***********学生信息如下***********");
System.out.println("学号:" + stu.getId() + "\n姓名:"
+ stu.getName() + "\n年龄:" + stu.getAge()
+ "\n性别:" + stu.getGender());
} catch (NameNotFoundException e) {
System.out.println(e.getMessage());
}
} else if ("c".equals(type)) {
System.out.println("请输入学号:");
int id = Integer.parseInt(br.readLine());
boolean flag = dao.delete(id);
if (flag) {
System.out.println("删除成功!");
} else {
System.out.println("删除失败!");
}
} else if ("exit".equals(type.toLowerCase())) {
System.out.println("系统正在退出...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
} else {
System.out.println("您的操作暂不支持,请重新输入:");
}
} } catch (IOException e) {
e.printStackTrace();
} finally {
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
代码均已经验证正确!