整个系统的结构是这个样子的。
总共大概三百行代码,供初学者学习。
<exam>
<student examid="1111" idcard="5555">
<name>张三name>
<location>上海location>
<grade>9grade>
student>
<student>
<name>李四name>
<location>大连location>
<grade>97grade>
student>
exam>
//StudentDao.java
package cn.itcast.dao;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import cn.itcast.domain.Student;
import cn.itcast.utils.XmlUtils;
/**
*
张三
沈阳
89
* @author Logan
*
*/
public class StudentDao {
public void add(Student student){
try{
Document document = XmlUtils.getDocument();
//student_node //ctrl+1 rename in file
Element student_node = document.createElement("student");
student_node.setAttribute("examid", student.getExamid());
student_node.setAttribute("idcard", student.getIdcard());
Element name = document.createElement("name");
name.setTextContent(student.getName());
Element location = document.createElement("location");
location.setTextContent(student.getLocation());
Element grade = document.createElement("grade");
grade.setTextContent(student.getGrade()+"");
student_node.appendChild(name);
student_node.appendChild(location);
student_node.appendChild(grade);
//得到exam节点,并把student挂上去
document.getElementsByTagName("exam").item(0).appendChild(student_node);
XmlUtils.write2Xml(document);
}catch(Exception e){
throw new RuntimeException(e);
}
}
//删除
public void delete(String name){
try{
Document document = XmlUtils.getDocument();
NodeList list = document.getElementsByTagName("name");
for(int i = 0;i
if(list.item(i).getTextContent().equals(name)){
list.item(i).getParentNode().getParentNode().removeChild(list.item(i).getParentNode());
XmlUtils.write2Xml(document);
return;
}
}
throw new RuntimeException("对不起,您要删除的学生不存在!");//异常也是一种返回值
}catch(Exception e){
throw new RuntimeException(e);
}
}
//查找
public Student find(String examid){
try{
Document document = XmlUtils.getDocument();
NodeList list = document.getElementsByTagName("student");
Student student = new Student();
for(int i = 0;i
Element student_node = (Element) list.item(i);
if(student_node.getAttribute("examid").equals(examid)){
Student s = new Student();
s.setExamid(examid);
student.setExamid(student_node.getAttribute("examid"));
student.setIdcard(student_node.getAttribute("idcard"));
s.setName(student_node.getElementsByTagName("name").item(0).getTextContent());
s.setGrade(Double.parseDouble(student_node.getElementsByTagName("grade").item(0).getTextContent()));
s.setLocation(student_node.getElementsByTagName("location").item(0).getTextContent());
return s;
}
}
return null;
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
//Student.java
package cn.itcast.domain;
public class Student {
private String idcard;
private String examid;
private String name;
private String location;
private Double grade;
//alt+shift+s
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
public String getExamid() {
return examid;
}
public void setExamid(String examid) {
this.examid = examid;
}
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;
}
}
//XmlUtils.java
package cn.itcast.utils;
import java.io.File;
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.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class XmlUtils {
public static Document getDocument() throws ParserConfigurationException, SAXException, IOException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new File("src/student.xml"));
}
public static void write2Xml(Document document) throws TransformerException{
TransformerFactory factory = TransformerFactory.newInstance();
Transformer tf = factory.newTransformer();
tf.transform(new DOMSource(document), new StreamResult(new File("src/student.xml")));
}
}
//Main.java
package cn.itcast.view;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import cn.itcast.dao.StudentDao;
import cn.itcast.domain.Student;
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.out.println("添加学生(a) 查找学生(b) 删除学生(c)");
System.out.print("请输入操作类型:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String type = br.readLine();
if(type.equalsIgnoreCase("a")){
//添加学生
try{
System.out.print("请输入学生姓名:");
String name = br.readLine();
System.out.print("请输入学生准考证号:");
String examid = br.readLine();
System.out.print("请输入学生身份证号:");
String idcard = br.readLine();
System.out.print("请输入学生所在地:");
String location = br.readLine();
System.out.print("请输入学生成绩:");
String grade = br.readLine();
Student student = new Student();
student.setExamid(examid);
student.setGrade(Double.parseDouble(grade));
student.setIdcard(idcard);
student.setLocation(location);
student.setName(name);
StudentDao dao = new StudentDao();
dao.add(student);
System.out.println("恭喜,添加成功!");
}catch(Exception e){
System.out.println("对不起,录入失败!");
}
}else if(type.equalsIgnoreCase("b")){
//查找学生
System.out.print("请输入查找的学生准考证号:");
String examid = br.readLine();
StudentDao dao = new StudentDao();
Student student = dao.find(examid);
if(student==null){
System.out.println("对不起,您要查找的学生不存在!");
}
else{
System.out.println("姓名:"+student.getName()+",身份证号:" +student.getIdcard()
+",准考证号:"+student.getExamid()+",地区:"+student.getLocation()+",成绩:"+student.getGrade());
}
}else if(type.equalsIgnoreCase("c")){
//删除学生
try{
System.out.print("请输入删除的学生姓名:");
String name = br.readLine();
StudentDao dao = new StudentDao();
dao.delete(name);
System.out.println("已删除"+name);
System.out.println("恭喜您,删除成功!");
}catch(Exception e){
System.out.println(e.getMessage());
}
}else{
System.out.println("非法字符");
}
}
}
该项目也可以使用DOM4j的API实现
下面是部分代码
//StudentDaoWithDOM4j
package cn.itcast.dao;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import cn.itcast.domain.Student;
import cn.itcast.utils.XmlUtilWithDom4j;
public class StudentDaoByDom4j {
public void add(Student student) throws Exception{
Document document = XmlUtilWithDom4j.getdocument();
Element root = document.getRootElement();
Element student_element = DocumentHelper.createElement("student");
Element name_element = DocumentHelper.createElement("name");
Element location_element = DocumentHelper.createElement("location");
Element grade_element = DocumentHelper.createElement("grade");
//student_element.addElement("name").setText(student.getName());这种方法也是可以的。
name_element.setText(student.getName());
location_element.setText(student.getLocation());
grade_element.setText(student.getGrade()+"");
student_element.addAttribute("examid", student.getExamid());
student_element.addAttribute("idcard", student.getIdcard());
student_element.add(name_element);
student_element.add(location_element);
student_element.add(grade_element);
root.add(student_element);
XmlUtilWithDom4j.write2xml(document);
}
public void delete(String name) throws Exception{
Document document = XmlUtilWithDom4j.getdocument();
Element root = document.getRootElement();
List list = document.getRootElement().elements("student");
for(int i = 0;i
Element student_element = (Element) list.get(i);
if(student_element.element("name").getText().equals(name)){
root.remove(student_element);
}
}
XmlUtilWithDom4j.write2xml(document);
}
public Student find(String examid) throws Exception{
Document document = XmlUtilWithDom4j.getdocument();
Element root = document.getRootElement();
Student student = new Student();
List list = document.getRootElement().elements("student");
for(int i = 0;i
Element student_element = (Element) list.get(i);
if(student_element.attributeValue("examid").equals(examid)){
student.setExamid(examid);
student.setIdcard(student_element.attributeValue("idcard"));
student.setGrade(Double.parseDouble(student_element.element("grade").getText()));
student.setLocation(student_element.element("location").getText());
student.setName(student_element.element("name").getText());
return student;
}
}
return null;
}
}
//XmlUtilWithDOM4j
package cn.itcast.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class XmlUtilWithDom4j {
public static Document getdocument() throws Exception{
SAXReader reader = new SAXReader();
Document document = reader.read(new File("src/student.xml"));
return document;
}
public static void write2xml(Document document) throws Exception, FileNotFoundException{
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileOutputStream("src/student.xml"));
writer.write(document);
writer.close();
}
}