xml的操作实例,考试管理系统——小小钟

本文介绍了一个使用XML文件来模拟数据库的简单系统实现。系统包括学生信息的增删查操作,利用Java进行数据读写,异常处理及单元测试等。通过这个例子,读者可以了解如何在没有数据库的情况下使用XML作为数据存储。

1.用xml模拟数据库,存储学生信息

<?xml version="1.0" encoding="UTF-8"?>
<exam>
	<student examid="111" idcard="111">
		<name>张三</name>
		<location>北京</location>
		<grade>99</grade>
	</student>

	<student examid="222" idcard="222">
		<name>李斯</name>
		<location>北京</location>
		<grade>80</grade>
	</student>

	<student examid="333" idcard="333">
		<name>aaa</name>
		<location>wuhan</location>
		<grade>89.0</grade>
	</student>
</exam>

2.操作数据库的DAO

package com.xxz.dao;

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

import com.xxz.domain.Student;
import com.xxz.exception.StudentNotExistException;
import com.xxz.utils.XmlUtils;

public class StudentDao {
	
	public void add(Student s){
		try {
			//得到文档对象
			Document doc = XmlUtils.getDocument();
			
			//创建student标签,并添加属性
			Element student_tag = doc.createElement("student");
			student_tag.setAttribute("idcard", s.getIdcard());
			student_tag.setAttribute("examid", s.getExamid());
			
			//创建name,location,grade并赋值
			Element name = doc.createElement("name");
			name.setTextContent(s.getName());
			Element location = doc.createElement("location");
			location.setTextContent(s.getLocation());
			Element grade = doc.createElement("grade");
			grade.setTextContent(s.getGrade()+"");
			
			//把name,location,grade添加为student的子标签
			student_tag.appendChild(name);
			student_tag.appendChild(location);
			student_tag.appendChild(grade);
			
			//把student标签添加到根标签exam下
			Element root = (Element) doc.getElementsByTagName("exam").item(0);
			root.appendChild(student_tag);
			
			XmlUtils.write2Xml(doc);
			System.out.println("添加成功!!!!");
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
	}
	
	public Student find(String examid){
		try {
			Document doc = XmlUtils.getDocument();
			
			NodeList list = doc.getElementsByTagName("student");
			for(int i=0; i<list.getLength(); i++){
				Element stu = (Element) list.item(i);
				String id = stu.getAttribute("examid");
				if(id.equals(examid)){
					String name = stu.getElementsByTagName("name").item(0).getTextContent();
					String location = stu.getElementsByTagName("location").item(0).getTextContent();
					String grade = stu.getElementsByTagName("grade").item(0).getTextContent();
					
					//创建一个student返回
					Student s = new Student();
					s.setExamid(examid);
					s.setIdcard(stu.getAttribute("idcard"));
					s.setName(name);
					s.setLocation(location);
					s.setGrade(Double.parseDouble(grade));
					
					return s;
				}
			}
			return null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public void delete(String name) throws StudentNotExistException{
		try {
			Document doc = XmlUtils.getDocument();
			
			NodeList list = doc.getElementsByTagName("name");
			for(int i=0;i<list.getLength();i++){
				Element nameElt = (Element) list.item(i);
				String nameStr = nameElt.getTextContent();
				if(nameStr.equals(name)){
					nameElt.getParentNode().getParentNode().removeChild(nameElt.getParentNode());
					XmlUtils.write2Xml(doc);
					System.out.println("删除成功!!!");
					return;
				}
			}
			throw new StudentNotExistException();
		}catch(StudentNotExistException ne){
			throw ne;
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

3.封装每个学生的javaBean

package com.xxz.domain;

public class Student {
	private String idcard;
	private String examid;
	private String name;
	private String location;
	private double grade;
	
	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;
	}
	
}

4.异常处理

package com.xxz.exception;

public class StudentNotExistException extends Exception {

	private static final long serialVersionUID = 1L;

	public StudentNotExistException() {}

	public StudentNotExistException(String message) {}

	public StudentNotExistException(Throwable cause) {}

	public StudentNotExistException(String message, Throwable cause) {}

	public StudentNotExistException(String message, Throwable cause,
			boolean enableSuppression, boolean writableStackTrace) {}

}

5.主程序

package com.xxz.ui;

import java.util.Scanner;

import com.xxz.dao.StudentDao;
import com.xxz.domain.Student;
import com.xxz.exception.StudentNotExistException;

public class Main {

	public static void main(String[] args) {
		
		System.out.println("添加学生(a)\t删除学生(b)\t查找学生(c)");
		System.out.print("请输入操作类型:");
		//try{
		//	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		//	String type = br.readLine();
		
			@SuppressWarnings("resource")
			Scanner sc = new Scanner(System.in);
			String type = sc.nextLine();
		
			StudentDao sd = new StudentDao();
			
			if("a".equals(type)){
					System.out.print("请输入准考证号:");
					//String examid = br.readLine();
					String examid = sc.nextLine();
					
					System.out.print("请输入身份证号:");
					//String idcard = br.readLine();
					String idcard = sc.nextLine();
					
					System.out.print("请输入姓名:");
					//String name = br.readLine();
					String name = sc.nextLine();
					
					System.out.print("请输入所在地:");
					//String location = br.readLine();
					String location = sc.nextLine();
					
					System.out.print("请输入成绩:");
					//String grade = br.readLine();
					String grade = sc.nextLine();
					
					Student s = new Student();
					s.setExamid(examid);
					s.setIdcard(idcard);
					s.setName(name);
					s.setLocation(location);
					s.setGrade(Double.parseDouble(grade));
					
					sd.add(s);
					
			}else if("b".equals(type)){
				try {
					System.out.print("请输入要删掉的学生姓名:");
					//String name = br.readLine();
					String name = sc.nextLine();
					sd.delete(name);
				} catch (StudentNotExistException e) {
					System.out.println("删除的学生不存在!!!");
				}
				
			}else if("c".equals(type)){
				System.out.print("请输入要查找的准考证号:");
				//String examid = br.readLine();
				String examid = sc.nextLine();
				Student s = sd.find(examid);
				if(s!=null){
					System.out.println("学生的身份证号:"+s.getIdcard());
					System.out.println("学生的准考证号:"+s.getExamid());
					System.out.println("学生的姓名:"+s.getName());
					System.out.println("学生的所在地:"+s.getLocation());
					System.out.println("学生的成绩:"+s.getGrade());
				}else {
					System.out.println("输入的准考证不存在!!!");
				}			
			}else {
				System.out.println("不支持此操作!!!");
			}
		//}catch(IOException ioe){
		//	System.out.println("对不起,出错了!!!");
		//}
	}

}

6.XML的工具类,用来操作XML

package com.xxz.utils;

import java.io.FileOutputStream;

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;

public class XmlUtils {
	
	private static String filename = "src/exam.xml";
	
	public static Document getDocument() throws Exception{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		return builder.parse(filename);
	}
	
	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(filename)));
	}
}

7.DAO类的测试

测试时要导入org.junit.Test包

package junit.test;

import org.junit.Test;

import com.xxz.dao.StudentDao;
import com.xxz.domain.Student;
import com.xxz.exception.StudentNotExistException;

public class StudentDaoTest {

	@Test
	public void testAdd(){
		Student s = new Student();
		s.setExamid("333");
		s.setIdcard("333");
		s.setName("aaa");
		s.setLocation("wuhan");
		s.setGrade(89);
		StudentDao sd = new StudentDao();
		sd.add(s);
	}
	
	@Test
	public void testFind(){
		StudentDao sd = new StudentDao();
		Student s = sd.find("333");
		if(s!=null){
			System.out.println(s.getIdcard());
			System.out.println(s.getExamid());
			System.out.println(s.getName());
			System.out.println(s.getLocation());
			System.out.println(s.getGrade());
		}else {
			System.out.println("准考证号码不存在!!!");
		}
	}
	
	@Test
	public void testDelete(){
		StudentDao sd = new StudentDao();
		try {
			sd.delete("aaa");
		} catch (StudentNotExistException e) {
			System.out.println("删除的学生不存在!!!");
		}
	}
}

虽然功能少了点,但是也是一个完整的程序


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值