首页 >> 网络营销词典 >> 互联网基础知识FAQ >> xml文件的增删改查

xml文件的增删改查[编辑]


最近,学习了 java 操作xml 文件。我就试着 写了一下对象到xml文件的增、删、改、查。可能还有些 不完美的地方,望大家多多指教。。。首先 ,定义一个类,封装 增、删、改、查方法
代码:
001
import java.io.File;
002
import java.io.PrintWriter;
003
import java.lang.reflect.Field;
004
import java.util.ArrayList;
005
import java.util.Arrays;
006
import java.util.List;
007

008
import javax.xml.parsers.DocumentBuilder;
009
import javax.xml.parsers.DocumentBuilderFactory;
010
import javax.xml.transform.Result;
011
import javax.xml.transform.Source;
012
import javax.xml.transform.Transformer;
013
import javax.xml.transform.TransformerFactory;
014
import javax.xml.transform.dom.DOMSource;
015
import javax.xml.transform.stream.StreamResult;
016

017
import org.w3c.dom.Document;
018
import org.w3c.dom.Element;
019
import org.w3c.dom.Node;
020
import org.w3c.dom.NodeList;
021

022

023
public class XmlUtil {
024
private Document document;//xml文档对象
025
private File f;//文件
026
private Class cl;//类
027

028
//get set方法
029
public Document getDocument() {
030
return document;
031
}
032

033
public void setDocument(Document document) {
034
this.document = document;
035
}
036

037
public File getF() {
038
return f;
039
}
040

041
public void setF(File f) {
042
this.f = f;
043
}
044

045

046

047
public Class getCl() {
048
return cl;
049
}
050

051
public void setCl(Class cl) {
052
this.cl = cl;
053
}
054

055
/**
056
* 得到xml document对象
057
* @param name
058
* @return
059
* @throws Exception
060
*/
061
public XmlUtil(String name,Class c)throws Exception{
062
f=new File(name);
063
if(!f.exists()){
064
System.out.println("该文件不存在!!!");
065
f.createNewFile();
066
String ss=c.getSimpleName().toLowerCase()+"s";
067
PrintWriter pw=new PrintWriter(f);
068
pw.println("");
069
pw.println("");
070
pw.println("");
071
pw.flush();
072
pw.close();
073
}
074
DocumentBuilderFactory df=DocumentBuilderFactory.newInstance();
075
DocumentBuilder db=df.newDocumentBuilder();
076
document=db.parse(f);
077
cl=c;
078
}
079

080
/**
081
* 保存 document 对象到xml文件中
082
* @throws Exception
083
*/
084

085
public void saveDocument() throws Exception{
086
Source source=new DOMSource(document);
087
TransformerFactory tf=TransformerFactory.newInstance();
088
Transformer tr=tf.newTransformer();
089
Result rs=new StreamResult(f);
090
tr.transform(source, rs);
091
}
092
/**
093
* 查询所有对象
094
* @throws IllegalAccessException
095
* @throws InstantiationException
096
*/
097
public List findAll() throws Exception{
098
NodeList ls=document.getElementsByTagName(cl.getSimpleName());
099
List list=new ArrayList();
100
for (int i = 0; i < ls.getLength(); i++) {
101
Object o=cl.newInstance();
102
Node n=ls.item(i);
103
NodeList ns=n.getChildNodes();
104
for (int j = 0; j < ns.getLength(); j++) {
105
Node n2=ns.item(j);
106
if(n2.getNodeType()==1){//元素节点
107
String nodeName=n2.getNodeName();
108
String nodeValue=n2.getTextContent();
109
Field [] fs=cl.getDeclaredFields();
110
for (int k = 0; k < fs.length; k++) {
111
if(fs[k].getName().equals(nodeName)){
112
fs[k].setAccessible(true);
113
String type=fs[k].getType().getSimpleName();
114
if(type.equals("int")){
115
fs[k].setInt(o, new Integer(nodeValue));
116
}else if(type.equals("float")){
117
fs[k].setFloat(o, new Float(nodeValue));
118
}else if(type.equals("double")){
119
fs[k].setDouble(o, new Double(nodeValue));
120
}else if(type.equals("short")){
121
fs[k].setShort(o, new Short(nodeValue));
122
}else if(type.equals("long")){
123
fs[k].setLong(o, new Long(nodeValue));
124
}else if(type.equals("byte")){
125
fs[k].setByte(o, new Byte(nodeValue));
126
}else if(type.equals("char")){
127
fs[k].setChar(o, new Character(nodeValue.toCharArray()[0]));
128
}else {
129
fs[k].set(o, nodeValue);
130
}
131
}
132
}
133
}
134
}
135
list.add(o);
136

137
}
138
System.out.println(list.size());
139
return list;
140
}
141

142
/**
143
* 根据id查询
144
*/
145
public Object get(int id)throws Exception{
146
int index=existsId(id);
147
String className=cl.getSimpleName();
148
Object o=null;
149
if(index>=0){
150
NodeList ns=document.getElementsByTagName(className).item(index).getChildNodes();
151
o=cl.newInstance();
152
for (int i = 0; i < ns.getLength(); i++) {
153
Node n=ns.item(i);
154
if(n.getNodeType()==1){//元素节点
155
String nodeName=n.getNodeName();
156
String nodeValue=n.getTextContent();
157
Field [] fs=cl.getDeclaredFields();
158
for (int k = 0; k < fs.length; k++) {
159
if(fs[k].getName().equals(nodeName)){
160
fs[k].setAccessible(true);
161
String type=fs[k].getType().getSimpleName();
162
if(type.equals("int")){
163
fs[k].setInt(o, new Integer(nodeValue));
164
}else if(type.equals("float")){
165
fs[k].setFloat(o, new Float(nodeValue));
166
}else if(type.equals("double")){
167
fs[k].setDouble(o, new Double(nodeValue));
168
}else if(type.equals("short")){
169
fs[k].setShort(o, new Short(nodeValue));
170
}else if(type.equals("long")){
171
fs[k].setLong(o, new Long(nodeValue));
172
}else if(type.equals("byte")){
173
fs[k].setByte(o, new Byte(nodeValue));
174
}else if(type.equals("char")){
175
fs[k].setChar(o, new Character(nodeValue.toCharArray()[0]));
176
}else {
177
fs[k].set(o, nodeValue);
178
}
179
}
180
}
181
}
182
}
183
}
184
return o;
185

186
}
187

188

189

190
/**
191
* 添加或修改
192
* @throws NoSuchFieldException
193
* @throws SecurityException
194
*/
195

196
public void saveOrUpdate(Object o) throws Exception{
197
Class c=o.getClass();
198
String className=c.getSimpleName();
199
Field field=c.getDeclaredField("id");
200
field.setAccessible(true);
201
int id=field.getInt(o);
202
if(existsId(id)>=0){//该对象存在
203
NodeList ls=document.getElementsByTagName(className);
204
for (int i = 0; i < ls.getLength(); i++) {
205
Node n=ls.item(i);
206
NodeList ns=n.getChildNodes();
207
for (int j = 0; j < ns.getLength(); j++) {
208
Node n2=ns.item(j);
209
if(n2.getNodeType()==1){
210
String nodeName=n2.getNodeName();
211
String nodeValue=n2.getTextContent();
212
if(nodeName.equals("id")&&nodeValue.equals(id+"")){
213
for(int k=0;k214
Node n3=ns.item(k);
215
if(n3.getNodeType()==1){
216
nodeName=n3.getNodeName();
217
nodeValue=n3.getTextContent();
218
Field[]fs=c.getDeclaredFields();
219
for (int l = 0; l < fs.length; l++) {
220
fs[l].setAccessible(true);
221
if(nodeName.equals(fs[l].getName())){
222
n3.setTextContent(fs[l].get(o)+"");
223
}
224
}
225
}
226
}
227
}
228
}
229

230
}
231
}
232
}else{//不存在
233
id=getMaxId();
234
// 以下代码手动创建节点
235
Element e= document.createElement(className);
236
Field []fs=c.getDeclaredFields();
237
for (int i = 0; i < fs.length; i++) {
238
fs[i].setAccessible(true);
239
if(fs[i].getName().equals("id")){
240
fs[i].set(o, id);
241
}
242
Element e2=document.createElement(fs[i].getName());
243
e2.appendChild(document.createTextNode(fs[i].get(o)+""));
244
e.appendChild(e2);
245
}
246

247

248
document.getDocumentElement().appendChild(e);
249
}
250
saveDocument();
251
}
252

253
/**
254
* 根据id删除
255
*
256
*/
257

258
public void delete(int id) throws Exception{
259
String className=cl.getSimpleName();
260
int index=existsId(id);
261
if(index>=0){//对象 存在
262
Node n=document.getElementsByTagName(className).item(index);
263
document.getDocumentElement().removeChild(n);
264
saveDocument();
265
}
266
}
267
/**
268
* 获得id
269
*/
270
public int getMaxId(){
271
String className=cl.getSimpleName();
272
NodeList ls=document.getElementsByTagName(className);
273
int id=0;
274
if(ls.getLength()==0){
275
return 1;
276
}else{
277
int []ids=new int[ls.getLength()];
278
for (int i = 0; i < ls.getLength(); i++) {
279
Node n=ls.item(i);
280
NodeList ns=n.getChildNodes();
281
for (int j = 0; j < ns.getLength(); j++) {
282
Node n2=ns.item(j);
283
if(n2.getNodeType()==1){
284
String nodeName=n2.getNodeName();
285
String nodeValue=n2.getTextContent();
286
if(nodeName.equals("id")){
287
ids[i]=Integer.parseInt(nodeValue);
288
}
289
}
290

291
}
292
}
293
Arrays.sort(ids);
294
id=ids[ids.length-1];
295
}
296
return id+1;
297
}
298
/**
299
* 判断 id 是否存在
300
*/
301
public int existsId(int id){
302
int index=-1;
303
String className=cl.getSimpleName();
304
NodeList ls=document.getElementsByTagName(className);
305
for (int i = 0; i < ls.getLength(); i++) {
306
Node n=ls.item(i);
307
NodeList ns=n.getChildNodes();
308
for (int j = 0; j < ns.getLength(); j++) {
309
Node n2=ns.item(j);
310
if(n2.getNodeType()==1){
311
String nodeName=n2.getNodeName();
312
String nodeValue=n2.getTextContent();
313
if(nodeName.equals("id")&&nodeValue.equals(id+"")){
314
index=i;
315
}
316
}
317

318
}
319
}
320
return index;
321
}
322
}
接下来定义一个 学生类 student :
01
/**
02
* 学生类
03
* @author Administrator
04
*
05
*/
06
public class Student {
07
private int id;//编号
08
private String name;//姓名
09
private String sex;//性别
10
private int age;//年龄
11
public int getId() {
12
return id;
13
}
14
public void setId(int id) {
15
this.id = id;
16
}
17
public String getName() {
18
return name;
19
}
20
public void setName(String name) {
21
this.name = name;
22
}
23
public String getSex() {
24
return sex;
25
}
26
public void setSex(String sex) {
27
this.sex = sex;
28
}
29
public int getAge() {
30
return age;
31
}
32
public void setAge(int age) {
33
this.age = age;
34
}
35

36

37
}
再写个 测试类 如下:
预览源代码打印
01
import java.util.List;
02

03

04

05
public class XMLTest {
06
public static void main(String[] args) throws Exception {
07

08
XmlUtil x=new XmlUtil("D://students.xml", Student.class);//传入 xml文件的路径 和 持久化对象的类
09

10
Student s=new Student();
11
s.setName("zs");
12
s.setSex("男");
13
s.setAge(20);
14
x.saveOrUpdate(s);//添加到xml文件
15

16
Liststudents=x.findAll();//查询xml文件,生成对象集合
17
for (Student student : students) {
18
System.out.println(student.getName());
19
}
20

21
//x.delete(20); //删除指定编号的对象
22

23
s.setId(1);
24
s.setName("ls");
25
s.setAge(22);
26
x.saveOrUpdate(s);//修改指定对象
27
}
28

29

30
}

 
参考资料:
扩展阅读:
相关词条:
合作编辑:

张明 

网络营销词典内容均由网友提供,仅供参考。如发现词条内容有问题,请发邮件至info # wm23.com。

词条信息

浏览次数:0

编辑次数:0历史版本

创建者:张明

最近更新:2014/3/17 2:57:15

词条分类导航

关于网络营销教学网站| 本站动态| 网站地图| 版权声明| 联系作者| 问题和建议|

版权声明:网络营销教学网站所有作品版权均归原作者所有,未经书面许可,严禁任何形式的转载/转贴、出版、篡改、汇编、编译等。