这里我们给出一份xml文档,里面存有一些学生的相关信息,我们需要对这份文档进行相关的解析。
1.首先给出student.xml
(xml/student.xml)
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<exam>
<student examid="222" idcard="111">
<name>张三</name>
<location>沈阳</location>
<grade>89</grade>
</student>
<student examid="444" idcard="333">
<name>李四</name>
<location>大连</location>
<grade>97</grade>
</student>
<student examid="5555" idcard="5555">
<name>阿猫</name>
<location>西安</location>
<grade>86.0</grade>
</student>
</exam>
2.学生实体类
(src/cn.itcast.domain.Student.java)
package cn.itcast.domain;
public class Student {
private String examId;
private String idcard;
private String name;
private String location;
private double grade;
public String getExamId() {
return examId;
}
public void setExamId(String examId) {
this.examId = examId;
}
public String getIdcard() {
return idcard;
}
public void setIdcard(String idcard) {
this.idcard = idcard;
}
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;
}
}
3.工具类
(src/cn.itcast.utils.XmlUtils.java)
package cn.itcast.utils;
import java.io.File;
import javax.management.RuntimeErrorException;
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;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import cn.itcast.domain.Student;
public class XmlUtils {
//将xml文档读到内存中
public static Document getDocument() throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("xml/student.xml"));
return document;
}
//将修改过的文档从内存中写到实际的xml文档中
public static void writeDocument(Document document) throws Exception{
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(new File("xml/student.xml")));
}
//添加学生
public void addStudent(Student student){
try{
Document document = XmlUtils.getDocument();
//得到exam节点
Node parent = document.getElementsByTagName("exam").item(0);
//构造一个学生节点
Element child = document.createElement("student");
child.setAttribute("examId", student.getExamId());
child.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");//注意:分数是double型的,需要转换成字符串
grade.setTextContent(student.getGrade() + "");
child.appendChild(name);
child.appendChild(location);
child.appendChild(grade);
parent.appendChild(child);
//将内存中的内容写到xml文档中去
XmlUtils.writeDocument(document);
}catch(Exception e){
throw new RuntimeException("录入失败!");
}
}
//删除学生
public void deleteStudent(String name) {
try{
Document document = XmlUtils.getDocument();
NodeList list = document.getElementsByTagName("name");
for(int i = 0; i < list.getLength(); i++){
Node node = list.item(i);
if(node.getTextContent().equals(name)){
//这里是删除student节点,即name的父节点
node.getParentNode().getParentNode().removeChild(node.getParentNode());
XmlUtils.writeDocument(document);
return;
}
}
throw new RuntimeException("您要删除的学生不存在!!!");
}catch(Exception e){
throw new RuntimeException("删除失败!!!");
}
}
//查找学生
public Student findStudent(String examid){
try {
Document document = XmlUtils.getDocument();
NodeList list = document.getElementsByTagName("student");
for(int i = 0; i < list.getLength(); i++){
//因为document中没有取得属性值的方法,所以要转换成Element对象
Element element = (Element) list.item(i);//取得其中一个学生节点
if(element.getAttribute("examid").equals(examid)){
Student student = new Student();
student.setExamId(examid);
student.setIdcard(element.getAttribute("idcard"));
student.setName(element.getElementsByTagName("name").item(0).getTextContent());
student.setLocation(element.getElementsByTagName("location").item(0).getTextContent());
student.setGrade(Double.parseDouble(element.getElementsByTagName("grade").item(0).getTextContent()));
return student;
}
}
return null;
} catch (Exception e) {
throw new RuntimeException("没有您想要查找的学生!!!");
}
}
}
4.测试类
(src/cn.itcast.Demo2.java)
package cn.itcast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.junit.Test;
import cn.itcast.domain.Student;
import cn.itcast.utils.XmlUtils;
public class Demo2 {
public static void main(String[] args) throws Exception{
System.out.println("(a)添加 (b)删除 (c)查找");
System.out.println("请输入您操作类型代号:");
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
String type = buffer.readLine();
//添加
if(type.equalsIgnoreCase("a")){
try{
Student stu = new Student();
System.out.println("请输入学生的姓名:");
stu.setName(buffer.readLine());
System.out.println("请输入学生的准考证号:");
stu.setExamId(buffer.readLine());
System.out.println("请输入学生的身份证号:");
stu.setIdcard(buffer.readLine());
System.out.println("请输入学生的地址:");
stu.setLocation(buffer.readLine());
System.out.println("请输入学生的分数:");
stu.setGrade(Double.parseDouble(buffer.readLine()));
XmlUtils utils = new XmlUtils();
utils.addStudent(stu);
System.out.println("录入成功!");
}catch(Exception e){
System.out.println(e.getMessage());
}
//删除
}else if(type.equalsIgnoreCase("b")){
try{
System.out.println("请输入您要删除学生的名字:");
String name = buffer.readLine();
XmlUtils utils = new XmlUtils();
utils.deleteStudent(name);
System.out.println("删除成功!");
}catch(Exception e){
System.out.println(e.getMessage());
}
//查找
}else if(type.equalsIgnoreCase("c")){
try{
System.out.println("请输入您想要查找学生的准考证号:");
String examid = buffer.readLine();
Student student = new Student();
XmlUtils utils = new XmlUtils();
student = utils.findStudent(examid);
System.out.println("您要找的学生的信息如下:");
System.out.println("学生姓名:" + student.getName());
System.out.println("学生准考证号:" + student.getExamId());
System.out.println("学生身份证号:" + student.getIdcard());
System.out.println("学生地址:" + student.getLocation());
System.out.println("学生分数:" + student.getGrade());
}catch(Exception e){
System.out.println("查找学生失败!");
}
}else{
System.out.println("没有您想要的操作!!!");
}
}
}
注意:这里我们需要注意删除学生的时候。而在异常抛出的时候我们需要注意抛出什么样的异常。而工具类中向上抛出的时候是抛到了测试类中了,我们使用e.getMessage()方法获得抛过来的异常消息。