Java如何使用xml做数据库

1.引用包 maven

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!--xml做数据库工具-->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.1</version>
</dependency>
<!-- 阿里的,类转map,map 转类-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.54</version>
</dependency>

2.数据库的xml文件

放到springboot 项目中的文件 taglibrary/src/main/resources/xmldatabase/userxml.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version="1.0" encoding="UTF-8"?>
<RECORDS>
<RECORD>
<id>1</id>
<username>用户名</username>
<deptId>部门</deptId>
<sex>男</sex>
<iconid>头像id</iconid>
<city>北京</city>
<password>password</password>
<onlinestate>状态</onlinestate>
<lastlogintime>最后登录时间</lastlogintime>
<registertime>时间</registertime>
</RECORD>
<RECORD>
<id>2021060715375511</id>
<username>2</username>
<deptId>1</deptId>
<sex>2</sex>
<iconid>2</iconid>
<city>1</city>
<password>2</password>
<onlinestate>2</onlinestate>
<lastlogintime>2</lastlogintime>
<registertime>2</registertime>
</RECORD>
</RECORDS>

3 application 配置xml地址和名称

1
2
xmldatabase.path = D:/ideaWorkspace/work20210607biaoqianku/taglibrary/src/main/resources/xmldatabase/
xmldatabase.userxml = userxml.xml

3 代码

UserxmlDao.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package com.taglibrary.platform.userxml;

import com.alibaba.fastjson.JSON;
import com.taglibrary.commonbase.BaseDao;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
*
*
* @author wjk
* @date 2021/06/09
*/

@Service
public class UserxmlDao extends BaseDao {

@Value("${xmldatabase.path}")
private String xmldatabasePath;
@Value("${xmldatabase.userxml}")
private String tableName;

/**
* 获取全部数据
* @return List<Userxml>
*/
public List<Userxml> getAll() {
List<Userxml> list = new ArrayList<Userxml>();
//定义一个reader和HashMap,HashMap是用来返回我们要查询的这个用户的信息的
SAXReader reader = new SAXReader();
try {

//得到user.xml的这个doc
Document doc = reader.read(new File(xmldatabasePath+tableName));
//得到所有用户的一个集合userList
List<Element> userList = doc.selectNodes("//RECORDS/RECORD");
//得到迭代器,
Iterator<Element> iter = userList.iterator();

while (iter.hasNext()) {
HashMap<String, String> map = new HashMap<String, String>();
//得到每一个user元素,进行判断
Element e = iter.next();
//如果这个user的ID和我们查询的ID一致,则将其所有的信息放入到map当中
//得到这个user的所有子元素
List<Element> childElements = e.elements();
//得到所有子元素的迭代器
Iterator<Element> childIter = childElements.iterator();
//如果还有子元素,则
while (childIter.hasNext()) {
//得到子元素,将其信息放入到map当中
Element childElement = childIter.next();
map.put(childElement.getQName().getName(), childElement.getText());
}
Userxml userxml = JSON.parseObject(JSON.toJSONString(map), Userxml.class);
list.add(userxml);
}
} catch (Exception e) {
e.printStackTrace();
logger.error(e.toString());
}
return list;
}
/**
* 查询
* @param Id
* @return Userxml
*/
public Userxml getOne(Long Id){
Userxml userxml = new Userxml();
List<Userxml> list = getAll();
for(int i = 0; i<list.size();i++){
Userxml userxmltmp = list.get(i);
if(userxmltmp.getId().toString().equals(Id.toString())){
userxml = userxmltmp;
break;
}
}
return userxml;
};

/**
* 增加
* @param userxml
* @return Userxml
*/
public Userxml insert(Userxml userxml){
try{
//读取文件
SAXReader saxReader = new SAXReader();
Document doc = saxReader.read(new File(xmldatabasePath+tableName));
//得到跟结点root
Element root = doc.getRootElement();
//往根节点添加user元素
Element element = root.addElement("RECORD");
//设置element的ID
element.addAttribute("id", userxml.getId().toString());

//往user添加各种子元素和设置值
Element Id = element.addElement("id");
Id.setText(userxml.getId().toString());
Element Username = element.addElement("username");
Username.setText(userxml.getUsername().toString());
Element Deptid = element.addElement("deptid");
Deptid.setText(userxml.getDeptid().toString());
Element Sex = element.addElement("sex");
Sex.setText(userxml.getSex().toString());
Element Iconid = element.addElement("iconid");
Iconid.setText(userxml.getIconid().toString());
Element City = element.addElement("city");
City.setText(userxml.getCity().toString());
Element Password = element.addElement("password");
Password.setText(userxml.getPassword().toString());
Element Onlinestate = element.addElement("onlinestate");
Onlinestate.setText(userxml.getOnlinestate().toString());
Element Lastlogintime = element.addElement("lastlogintime");
Lastlogintime.setText(userxml.getLastlogintime().toString());
Element Registertime = element.addElement("registertime");
Registertime.setText(userxml.getRegistertime().toString());

//添加元素结束后往新的文件重新写入doc数据
XMLWriter output = new XMLWriter(new FileWriter( new File(xmldatabasePath+tableName) ));
output.write(doc);
//关闭输出流
output.close();

}

catch(DocumentException e){
e.printStackTrace();
}

catch(IOException e){
e.printStackTrace();
}
return userxml;
}
/**
* 删除
* @param Id
* @return Userxml
*/
public Userxml delete(Long Id){
Userxml userxml = new Userxml();
SAXReader reader = new SAXReader();
try {
//得到user.xml的Document
Document doc = reader.read(new File(xmldatabasePath+tableName));
//得到跟结点
Element root = doc.getRootElement();
//得到根节点下的所有user集合
List<Element> userList = doc.selectNodes("//RECORDS/RECORD");
//得到迭代器
Iterator<Element> iter = userList.iterator();
while(iter.hasNext()){
HashMap<String, String> map = new HashMap<String, String>();
//得到user元素
Element e = iter.next();
//得到这个user的所有子元素
List<Element> childElements = e.elements();
//得到所有子元素的迭代器
Iterator<Element> childIter = childElements.iterator();
//如果还有子元素,则
while (childIter.hasNext()) {
//得到子元素,将其信息放入到map当中
Element childElement = childIter.next();
map.put(childElement.getQName().getName(), childElement.getText());
}
Userxml userxmlTmp = JSON.parseObject(JSON.toJSONString(map), Userxml.class);
if(userxmlTmp.getId() == Id){
root.remove(e);
userxml = userxmlTmp;
}
}
//得到XML的输出流
XMLWriter output;
try {
output = new XMLWriter(new FileWriter( new File(xmldatabasePath+tableName) ));
//将内存中的doc写入到新文件当中
output.write(doc);
//关闭输出流
output.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (DocumentException e) {
e.printStackTrace();
}
return userxml;
}

/**
* 修改
* @param userxml
* @return userxml
*/
public Userxml update(Userxml userxml){
try {
//得到user.xml文件,将其读取到doc当中
SAXReader reader = new SAXReader();
Document doc = reader.read(new File(xmldatabasePath+tableName));
//得到跟结点root
Element root = doc.getRootElement();
//得到根节点TUser下的所有用户,将其存放到userList当中
List<Element> userList = doc.selectNodes("//RECORDS/RECORD");
//得到可以访问所有用户的迭代器Iterator
Iterator<Element> iter = userList.iterator();
//如果迭代器还有下一个,则取出来
while(iter.hasNext()){
HashMap<String, String> map = new HashMap<String, String>();

//得到user元素
Element e = iter.next();
//得到这个user的所有子元素
List<Element> childElements = e.elements();
//得到所有子元素的迭代器
Iterator<Element> childIter = childElements.iterator();
//如果还有子元素,则
while (childIter.hasNext()) {
//得到子元素,将其信息放入到map当中
Element childElement = childIter.next();
map.put(childElement.getQName().getName(), childElement.getText());
}
Userxml userxmlTmp = JSON.parseObject(JSON.toJSONString(map), Userxml.class);
if(userxml.getId() == userxmlTmp.getId()){
Class cls = userxml.getClass();
Field[] fields = cls.getDeclaredFields();
for(int i=0; i<fields.length; i++){
Field f = fields[i];
f.setAccessible(true);
Element childElement = e.element(f.getName());
try {
childElement.setText(f.get(userxml).toString());
} catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
}
}
//得到XML的输出流
XMLWriter output;
try {
output = new XMLWriter(new FileWriter( new File(xmldatabasePath+tableName) ));
//将内存中的doc写入到新文件当中
output.write(doc);
//关闭输出流
output.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (DocumentException e) {
e.printStackTrace();
}
return userxml;
}

}

UserxmlController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package com.taglibrary.platform.userxml;

import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mybatis.logging.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.context.annotation.Scope;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.List;

import com.taglibrary.commonbase.BaseController;
import com.taglibrary.util.ReturnDataJson;

import com.taglibrary.platform.userxml.Userxml;
import com.taglibrary.platform.userxml.UserxmlService;
/**
*
*
* @author wjk
* @date 2021/06/09
*/
@Controller
@Scope("request")
@RequestMapping("/userxml")
@Api(value = "", tags = {""})
public class UserxmlController extends BaseController {

@Resource
private UserxmlService service;

@Resource
private UserxmlDao dao;

/**
* 查询(获取全部)
*/
@RequestMapping(value = "/getAll",method=RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "查询(获取全部)")
public ReturnDataJson getall() {
ReturnDataJson res;
try {
List<Userxml> list = this.dao.getAll();
res = this.responseReturnDataJson(true,"成功",list,Long.valueOf(list.size()));
} catch (Exception e) {
logger.error(e.getMessage(), e);
res = this.responseReturnDataJson(false,"失败");
}
return res;
}


/**
* 查询(根据id)
*/
@RequestMapping(value = "/detail",method=RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "查询(根据id)")
public ReturnDataJson detail(@RequestBody Userxml userxml) {
ReturnDataJson res;
try {
Userxml olduserxml= this.dao.getOne(userxml.getId());
if(olduserxml.getId() == null){
res = this.responseReturnDataJson(false,"失败","未查询到数据(id="+userxml.getId().toString()+")");
} else{
res = this.responseReturnDataJson(true,"成功");
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
res = this.responseReturnDataJson(false,"失败");
}
return res;
}
/**
* 增加
**/
@RequestMapping(value = "/add",method=RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "增加")
public ReturnDataJson add(@RequestBody Userxml userxml) {
ReturnDataJson res;
try {
Userxml olduserxml= this.dao.getOne(userxml.getId());
if(olduserxml.getId() == null){
Userxml newuserxml= this.dao.insert(userxml);
res = this.responseReturnDataJson(true,"成功",newuserxml);
} else{
res = this.responseReturnDataJson(false,"失败","已有数据(id="+olduserxml.getId().toString()+")");
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
res = this.responseReturnDataJson(false,"失败");
}
return res;
}

/**
* 修改
**/
@RequestMapping(value = "/update",method=RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "修改(根据id)")
public ReturnDataJson update(@RequestBody Userxml userxml) {
ReturnDataJson res;
try {
Userxml olduserxml= this.dao.getOne(userxml.getId());
if(olduserxml.getId() == null){
res = this.responseReturnDataJson(false,"失败","未查询到数据(id="+userxml.getId().toString()+")");
} else{
Userxml newuserxml= this.dao.update(userxml);
res = this.responseReturnDataJson(true,"成功",newuserxml);
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
res = this.responseReturnDataJson(false,"失败");
}
return res;
}

/**
* 删除(根据id)
**/
@RequestMapping(value = "/delete",method=RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "删除(根据id)")
public ReturnDataJson delete(@RequestBody Userxml userxml) {
ReturnDataJson res;
try {
Userxml olduserxml= this.dao.getOne(userxml.getId());
if(olduserxml.getId() == null){
res = this.responseReturnDataJson(false,"失败","未查询到数据(id="+userxml.getId().toString()+")");
} else{
Userxml newuserxml= this.dao.delete(userxml.getId());
res = this.responseReturnDataJson(true,"成功");
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
res = this.responseReturnDataJson(false,"失败");
}
return res;
}

}
继开 wechat
欢迎加我的微信,共同交流技术