這里我們給出一份xml文檔,里面存有一些學生的相關(guān)信息震桶,我們需要對這份文檔進行相關(guān)的解析尖奔。
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文檔讀到內(nèi)存中
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;
}
//將修改過的文檔從內(nèi)存中寫到實際的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節(jié)點
Node parent = document.getElementsByTagName("exam").item(0);
//構(gòu)造一個學生節(jié)點
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");//注意:分數(shù)是double型的,需要轉(zhuǎn)換成字符串
grade.setTextContent(student.getGrade() + "");
child.appendChild(name);
child.appendChild(location);
child.appendChild(grade);
parent.appendChild(child);
//將內(nèi)存中的內(nèi)容寫到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節(jié)點,即name的父節(jié)點
node.getParentNode().getParentNode().removeChild(node.getParentNode());
XmlUtils.writeDocument(document);
return;
}
}
throw new RuntimeException("您要刪除的學生不存在5钊纭9鄙骸!");
}catch(Exception e){
throw new RuntimeException("刪除失斏婺佟C挪怼!烤送!");
}
}
//查找學生
public Student findStudent(String examid){
try {
Document document = XmlUtils.getDocument();
NodeList list = document.getElementsByTagName("student");
for(int i = 0; i < list.getLength(); i++){
//因為document中沒有取得屬性值的方法寒随,所以要轉(zhuǎn)換成Element對象
Element element = (Element) list.item(i);//取得其中一個學生節(jié)點
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("沒有您想要查找的學生!0锛帷牢裳!");
}
}
}
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("請輸入學生的分數(shù):");
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("學生分數(shù):" + student.getGrade());
}catch(Exception e){
System.out.println("查找學生失斊蜒丁!");
}
}else{
System.out.println("沒有您想要的操作;沂稹E邪铩!");
}
}
}
注意:這里我們需要注意刪除學生的時候溉箕。而在異常拋出的時候我們需要注意拋出什么樣的異常晦墙。而工具類中向上拋出的時候是拋到了測試類中了,我們使用e.getMessage()方法獲得拋過來的異常消息肴茄。