JavaWeb学习(六)

XML练习案例

exam.xml 充当数据库

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<exam>
	<student idcard="111" examid="222">
		<name>张三</name>
		<location>沈阳</location>
		<grade>89</grade>
	</student>
	
	<student idcard="333" examid="444">
		<name>李四</name>
		<location>大连</location>
		<grade>97</grade>
	</student>
</exam>

模块划分图

用户
cn.itcast.UI
main.java
用户界面
cn.itcast.dao
StudentDao
数据访问对象
Date access Object
cn.itcast.domain
cn.itcast.bean
cn.itcast.entity
封装对象
exam.xml
数据库
XmlUtils
工具类
get&write

代码

Student.java 对象

package cn.itcast.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;
	}
}

XmlUtils.java 工具

package cn.itcast.utils;

import java.io.FileOutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
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;
import org.xml.sax.SAXException;

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 document) throws Exception {
		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer tf = factory.newTransformer();
		tf.transform(new DOMSource(document), (Result) new StreamResult(new FileOutputStream(filename)));
	}
}

StudentDao.java 方法

package cn.itcast.dao;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import cn.itcast.domain.Student;
import cn.itcast.exception.StudentNotExistException;
import cn.itcast.utils.XmlUtils;

public class StudentDao {
	
	public void add(Student s) {
		try {
			Document document = XmlUtils.getDocument();
			//创建封装学生信息的标签
			Element student_tag = document.createElement("student");
			student_tag.setAttribute("idcard", s.getIdcard());
			student_tag.setAttribute("examid", s.getExamid());
			
			//创建封装学生姓名、所在地和成绩的标签
			Element name = document.createElement("name");
			Element location = document.createElement("location");
			Element grade = document.createElement("grade");
			
			name.setTextContent(s.getName());
			location.setTextContent(s.getLocation());
			grade.setTextContent(s.getGrade()+"");		//任何与字符串相加可转换为字符串
			
			student_tag.appendChild(name);
			student_tag.appendChild(location);
			student_tag.appendChild(grade);
			
			//把封装了信息的学生标签挂到文档上
			document.getElementsByTagName("exam").item(0).appendChild(student_tag);
			
			//更新内存
			XmlUtils.write2Xml(document);
		} catch (Exception e) {
			throw new RuntimeException(e);		//转型为运行时异常
		}		//编译时异常
	}
	
	public Student find(String examid) {
		try {
			Document document = XmlUtils.getDocument();
			NodeList list = document.getElementsByTagName("student");
			for(int i = 0; i < list.getLength(); i++) {
				Element student_tag = (Element) list.item(i);
				if(student_tag.getAttribute("examid").equals(examid)) {
					//找到与examid匹配的学生,new一个student对象封装这个学生信息返回
					Student s = new Student();
					s.setExamid(examid);
					s.setIdcard(student_tag.getAttribute("idcard"));
					s.setName(student_tag.getElementsByTagName("name").item(0).getTextContent());
					s.setLocation(student_tag.getElementsByTagName("location").item(0).getTextContent());
					s.setGrade(Double.parseDouble(student_tag.getElementsByTagName("grade").item(0).getTextContent()));
					return s;
				}
			}
			return null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public void delete(String name) throws StudentNotExistException {
		try {
			Document document = XmlUtils.getDocument();
			NodeList list = document.getElementsByTagName("name");
			for(int i = 0; i < list.getLength(); i++) {
				if(list.item(i).getTextContent().equals(name)) {
					list.item(i).getParentNode().getParentNode().removeChild(list.item(i).getParentNode());
					XmlUtils.write2Xml(document);
					return;
				}
			}
			throw new StudentNotExistException(name + "不存在");
		} catch (StudentNotExistException e) {
			throw e;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

StudentNotExistException.java 异常

package cn.itcast.exception;

public class StudentNotExistException extends Exception {

	public StudentNotExistException() {
		// TODO Auto-generated constructor stub
	}

	public StudentNotExistException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	public StudentNotExistException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}

	public StudentNotExistException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}

	public StudentNotExistException(String message, Throwable cause, boolean enableSuppression,
			boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
		// TODO Auto-generated constructor stub
	}
}

StudentDaoTest.java 测试

package junit.test;

import org.junit.Test;

import cn.itcast.dao.StudentDao;
import cn.itcast.domain.Student;
import cn.itcast.exception.StudentNotExistException;

public class StudentDaoTest {

	@Test
	public void testAdd() {
		StudentDao dao = new StudentDao();
		Student s = new Student();
		s.setExamid("121");
		s.setGrade(89);
		s.setIdcard("121");
		s.setLocation("北京");
		s.setName("aa");
		dao.add(s);
	}
	
	@Test
	public void testFind() {
		StudentDao dao = new StudentDao();
		dao.find("121");
		
	}
	
	@Test
	public void testDelete() throws StudentNotExistException {
		StudentDao dao = new StudentDao();
		dao.delete("aa");
	}
}

Main.java 主程序

package cn.itcast.UI;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import cn.itcast.dao.StudentDao;
import cn.itcast.domain.Student;
import cn.itcast.exception.StudentNotExistException;

public class Main {

	public static void main(String[] args) {
		try {
			System.out.println("添加学生(a)    删除学生(b)   查找学生(c)");
			System.out.print("请输出操作类型:");
			
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String type = br.readLine();
			
			if("a".equals(type)) {
				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 s = new Student();
				s.setExamid(examid);
				s.setGrade(Double.parseDouble(grade));
				s.setIdcard(idcard);
				s.setLocation(location);
				s.setName(name);
				
				StudentDao dao = new StudentDao();
				dao.add(s);
				
				System.out.println("添加成功");
			}else if("b".equals(type)) {
				System.out.print("请输入要删除的学生姓名:");
				String name = br.readLine();
				
				try {
					StudentDao dao = new StudentDao();
					dao.delete(name);
					System.out.println("删除成功");
				} catch(StudentNotExistException e) {
					System.out.print("您要删除的学生不存在");
				}
				
			}else if("c".equals(type)) {
				System.out.print("请输入要查找的学生准考证号:");
				String examid = br.readLine();
				
				StudentDao dao = new StudentDao();
				Student s = new Student();
				s = dao.find(examid);
				System.out.println("您查询的学生信息为:");
				System.out.println("姓名:"+s.getName()+",身份证号:"+s.getIdcard()+",准考证号:"+s.getExamid()+",地区:"+s.getLocation()+",成绩:"+s.getGrade());
				System.out.println("查找完毕");
			}else {
				System.out.println("对不起,不支持您的操作");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("对不起,出现错误");
		}
	}
}

结果

初始界面:

初始界面

添加学生 - 操作a:

添加学生 - 操作a

更新后的exam.xml文档:

更新后的exam.xml文档

删除学生 - 操作b:

删除学生 - 操作b

更新后的exam.xml文档:

更新后的exam.xml文档

查找学生 - 操作c:

查找学生 - 操作c

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值