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>
模块划分图
代码
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("对不起,出现错误");
}
}
}