利用 JAXP 对 XML文件 的处理,把xml当做一个数据库来对待
Student对象定义类
![](https://img-blog.csdnimg.cn/img_convert/11f30e04b971185e297223b870302346.gif)
![](https://img-blog.csdnimg.cn/img_convert/6123e5b4dc3429f1d61eb3628186c221.gif)
public class Student {
private String idcard;//身份证号
private String examid;//准考证号
private String name;//姓名
private String location;//籍贯
private float grade;//成绩
public Student(){}
public Student(String idcard, String examid, String name, String location,
float grade) {
super();
this.idcard = idcard;
this.examid = examid;
this.name = name;
this.location = location;
this.grade = 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 float getGrade() {
return grade;
}
public void setGrade(float grade) {
this.grade = grade;
}
@Override
public String toString() {
return "Student [idcard=" + idcard + ", examid=" + examid + ", name="
+ name + ", location=" + location + ", grade=" + grade + "]";
}
}
StudentDao 接口类
//原则:抽象和实现分离
//根据功能要求
//接口中的每个方法:注释要写的清清楚楚,做到没有歧义
![](https://img-blog.csdnimg.cn/img_convert/3ef90c97ceb0409ee180e9fe17876953.gif)
![](https://img-blog.csdnimg.cn/img_convert/510872ca26683285e1d287406860d4e5.gif)
1 public interface StudentDao {
2
3 /**
4
5 * 添加学生信息到数据库
6
7 * @param s 封装了要保存的信息的学生对象
8
9 * @return 成功了返回true,否则false
10
11 */
12
13 boolean addStudent(Student s);
14
15 /**
16
17 * 根据准考证号查询学生的信息
18
19 * @param examid 准考证号
20
21 * @return 没有找到返回null
22
23 */
24
25 Student findByExamid(String examid);
26
27 /**
28
29 * 根据姓名删除学生信息
30
31 * @param name 学生的姓名
32
33 * @return 删除成功返回true。删除失败或学生不存在都返回false
34
35 */
36
37 boolean delStudentByName(String name);
38
39 }
StudentDaoimpl 实现类
![](https://img-blog.csdnimg.cn/img_convert/40bc18c5011980d75266d1fddd3a9736.gif)
![](https://img-blog.csdnimg.cn/img_convert/8216cbc6fba56272f087a3c338453bc1.gif)
1 public class StudentDaoImpl implements StudentDao {
2
3
4
5 public boolean addStudent(Student s) {
6
7 boolean result = false;
8
9 try {
10
11 //得到Document对象
12
13 Document doc = JaxpUtil.getDocument();//异常怎么办?抛:调用者得有能力处理。处理
14
15 //创建<student>:设置属性
16
17 Element studentE = doc.createElement("student");//<student></student>
18
19 studentE.setAttribute("idcard", s.getIdcard());
20
21 studentE.setAttribute("examid", s.getExamid());//<student idcard="370101" examid="438">
22
23 //依次创建<name><location><grade>并设置主体内容
24
25 Element nameE = doc.createElement("name");//<name></name>
26
27 nameE.setTextContent(s.getName());// <name>郭美美</name>
28
29
30
31 Element locationE = doc.createElement("location");
32
33 locationE.setTextContent(s.getLocation());
34
35
36
37 Element gradeE = doc.createElement("grade");
38
39 gradeE.setTextContent(s.getGrade()+"");
40
41 //建立与student元素的父子关系
42
43 studentE.appendChild(nameE);
44
45 studentE.appendChild(locationE);
46
47 studentE.appendChild(gradeE);
48
49 //把student挂接到根元素上
50
51 Node rootNode = doc.getElementsByTagName("exam").item(0);
52
53 rootNode.appendChild(studentE);
54
55 //写回xml文档中
56
57 JaxpUtil.write2xml(doc);
58
59 result = true;
60
61 } catch (Exception e) {
62
63 throw new RuntimeException(e);//编译时异常--》运行时异常:异常转义;异常链
64
65 }
66
67 return result;
68
69 }
70
71
72
73 public Student findByExamid(String examid) {
74
75 Student s = null;
76
77 try {
78
79 //得到Document对象
80
81 Document doc = JaxpUtil.getDocument();
82
83 //得到所有的<student>元素
84
85 NodeList nl = doc.getElementsByTagName("student");
86
87 //遍历:判断属性的值和参数的值是否相等
88
89 for(int i=0;i<nl.getLength();i++){
90
91 //相等:读取属性和子元素的文本,封装到Student对象中
92
93 Node node = nl.item(i);
94
95 if(node.getNodeType()==Node.ELEMENT_NODE){
96
97 Element e = (Element)node;
98
99 if(e.getAttribute("examid").equals(examid)){
100
101 s = new Student();
102
103 s.setIdcard(e.getAttribute("idcard"));
104
105 s.setExamid(examid);
106
107 s.setName(e.getElementsByTagName("name").item(0).getTextContent());
108
109 s.setLocation(e.getElementsByTagName("location").item(0).getTextContent());
110
111 s.setGrade(Float.parseFloat(e.getElementsByTagName("grade").item(0).getTextContent()));
112
113 break;
114
115 }
116
117 }
118
119 }
120
121 //返回数据
122
123 } catch (Exception e) {
124
125 throw new RuntimeException(e);//编译时异常--》运行时异常:异常转义;异常链
126
127 }
128
129 return s;
130
131 }
132
133
134
135 public boolean delStudentByName(String name) {
136
137 boolean result = false;
138
139 try {
140
141 //得到Document对象
142
143 Document doc = JaxpUtil.getDocument();
144
145 //得到所有的name元素
146
147 NodeList nl = doc.getElementsByTagName("name");
148
149 //遍历:判断元素的文本和参数是否相等
150
151 for(int i=0;i<nl.getLength();i++){
152
153 Node node = nl.item(i);
154
155 if(node.getTextContent().equals(name)){
156
157 //如果是:爷爷干掉爸爸
158
159 node.getParentNode().getParentNode().removeChild(node.getParentNode());
160
161 //写回xml文档
162
163 JaxpUtil.write2xml(doc);
164
165 //设置标记为true
166
167 result = true;
168
169 }
170
171 }
172
173 } catch (Exception e) {
174
175 throw new RuntimeException(e);//编译时异常--》运行时异常:异常转义;异常链
176
177 }
178
179 return result;
180
181 }
182
183
184
185 }
JavaUtil
//工具类
//异常可以处理:不给调用者添麻烦
//可以抛:谁用谁处理
![](https://img-blog.csdnimg.cn/img_convert/0313c5a471d1b25eaf59253c2e3b2430.gif)
![](https://img-blog.csdnimg.cn/img_convert/972fad383166d46cbb22f7669ed2c867.gif)
1 public class JaxpUtil {
2
3 public static Document getDocument() throws ParserConfigurationException, SAXException, IOException{
4
5 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
6
7 DocumentBuilder builder = dbf.newDocumentBuilder();//异常怎么办?哲学问题
8
9 Document document = builder.parse("src/exam.xml");
10
11 return document;
12
13 }
14
15 public static void write2xml(Document document) throws TransformerException{
16
17 TransformerFactory tf = TransformerFactory.newInstance();
18
19 Transformer ts = tf.newTransformer();
20
21 ts.transform(new DOMSource(document), new StreamResult("src/exam.xml"));
22
23 }
24
25 }
StudentDaoImplTest 测试类
![](https://img-blog.csdnimg.cn/img_convert/1967d8cfa32fad4274d07a9647174a03.gif)
![](https://img-blog.csdnimg.cn/img_convert/9f2835dec21752989dca5970eae50d14.gif)
1 public class StudentDaoImplTest {
2
3 public static void main(String[] args) {
4
5 StudentDao dao = new StudentDaoImpl();
6
7
8
9 // Student s = new Student();
10
11 // s.setExamid("999");
12
13 // s.setIdcard("1101");
14
15 // s.setName("牛骞");
16
17 // s.setLocation("河南");
18
19 // s.setGrade(100);
20
21 // dao.addStudent(s);
22
23
24
25 Student s = dao.findByExamid("999");
26
27 System.out.println(s);
28
29
30
31 // boolean b = dao.delStudentByName("牛骞");
32
33 // System.out.println(b);
34
35 }
|