Java操作XML(使用org.w3c.dom)
一、创建DOM
?
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
XMLBuilder.java
用于创建DOM,Root结点
/********************************************************************
* 项目名称 :rochoc
* 包名称 :rochoc.xml.oper
* 文件名称 :XmlBuilder
* 编写者 :luoc
* 编写日期 :2005-6-22
* 程序功能(类)描述 : 根据传入的XML文件生成Document和root结点
*
* 程序变更日期 :
* 变更作者 :
* 变更说明 :
********************************************************************/
packagerochoc.xml.oper;
importjava.io.File;
importjava.io.IOException;
importjavax.xml.parsers.DocumentBuilder;
importjavax.xml.parsers.DocumentBuilderFactory;
importjavax.xml.parsers.ParserConfigurationException;
importorg.apache.log4j.Logger;
importorg.w3c.dom.Document;
importorg.w3c.dom.Element;
importorg.xml.sax.SAXException;
/**
* 类名:XmlBuilder
* 类描述:根据传入的XML文件生成Document和root结点
* 编写者 :luoc
* 编写日期 :2005-6-22
* 主要public成员变量:
* 主要public方法:
**/
publicclassXmlBuilder
{
/**
*构造函数说明:
*参数说明:@param path
**/
publicXmlBuilder(String path)
{
this.path=path;
init();
}
/**
* 方法名称:init
* 方法功能:初始化函数
* 参数说明:
* 返回:void
* 作者:luoc
* 日期:2005-6-22
**/
publicvoidinit()
{
buildDocument();
buildRoot();
}
/**
* 方法名称:buildDocument
* 方法功能:将XML文件生成Document
* 参数说明:
* 返回:void
* 作者:luoc
* 日期:2005-6-22
**/
privatevoidbuildDocument()
{
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder builder=factory.newDocumentBuilder();
logger.debug("Construct document builder success.");
doc=builder.parse(newFile(path));
logger.debug("Build xml document success.");
}catch(ParserConfigurationException e)
{
logger.error("Construct document builder error:"+e);
}catch(SAXException e)
{
logger.error("Parse xml file error:"+e);
}catch(IOException e)
{
logger.error("Read xml file error:"+e);
}
}
/**
* 方法名称:buildRoot
* 方法功能:生成XML的根结点
* 参数说明:
* 返回:void
* 作者:luoc
* 日期:2005-6-22
**/
privatevoidbuildRoot()
{
root=doc.getDocumentElement();
}
/**
* @return 返回 doc。
*/
publicDocument getDoc()
{
returndoc;
}
/**
* @param doc 要设置的 doc。
*/
publicvoidsetDoc(Document doc)
{
this.doc = doc;
}
/**
* @return 返回 path。
*/
publicString getPath()
{
returnpath;
}
/**
* @param path 要设置的 path。
*/
publicvoidsetPath(String path)
{
this.path = path;
}
/**
* @return 返回 root。
*/
publicElement getRoot()
{
returnroot;
}
/**
* @param root 要设置的 root。
*/
publicvoidsetRoot(Element root)
{
this.root = root;
}
/*全局变量*/
privateString path=null;//xml文件路径
privateDocument doc=null;//xml文件对应的document
privateElement root=null;//xml文件的根结点
privateLogger logger=Logger.getLogger(getClass().getName());
}
二、查找,插入,删除,修改
?
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
XmlOper.java
用于操作XML文件,包括查找、新增、删除、修改结点
/********************************************************************
* 项目名称 :rochoc
* 包名称 :rochoc.xml.oper
* 文件名称 :XmlOper
* 编写者 :luoc
* 编写日期 :2005-6-22
* 程序功能(类)描述 : 对XML进行读写操作
*
* 程序变更日期 :
* 变更作者 :
* 变更说明 :
********************************************************************/
packagerochoc.xml.oper;
importjava.util.ArrayList;
importorg.apache.log4j.Logger;
importorg.w3c.dom.Document;
importorg.w3c.dom.Element;
importorg.w3c.dom.Node;
importorg.w3c.dom.NodeList;
/**
* 类名:XmlOper
* 类描述:对XML文件进行读写操作,均为静态函数
* 编写者 :luoc
* 编写日期 :2005-6-22
* 主要public成员变量:
* 主要public方法:
**/
publicclassXmlOper
{
/**
*构造函数说明:
*参数说明:
**/
privateXmlOper()
{
}
/**
* 方法名称:getNodeList
* 方法功能:获取父结点parent的所有子结点
* 参数说明:@param parent
* 参数说明:@return
* 返回:NodeList
* 作者:luoc
* 日期:2005-6-22
**/
publicstaticNodeList getNodeList(Element parent)
{
returnparent.getChildNodes();
}
/**
* 方法名称:getElementsByName
* 方法功能:在父结点中查询指定名称的结点集
* 参数说明:@param parent
* 参数说明:@param name
* 参数说明:@return
* 返回:Element[]
* 作者:luoc
* 日期:2005-6-22
**/
publicstaticElement [] getElementsByName(Element parent,String name)
{
ArrayList resList=newArrayList();
NodeList nl=getNodeList(parent);
for(inti=0;i
{
Node nd=nl.item(i);
if(nd.getNodeName().equals(name))
{
resList.add(nd);
}
}
Element [] res=newElement [resList.size()];
for(inti=0;i
{
res[0]=(Element)resList.get(i);
}
logger.debug(parent.getNodeName()+"'s children of "+name+
"'s num:"+res.length);
returnres;
}
/**
* 方法名称:getElementName
* 方法功能:获取指定Element的名称
* 参数说明:@param element
* 参数说明:@return
* 返回:String
* 作者:luoc
* 日期:2005-6-22
**/
publicstaticString getElementName(Element element)
{
returnelement.getNodeName();
}
/**
* 方法名称:getElementValue
* 方法功能:获取指定Element的值
* 参数说明:@param element
* 参数说明:@return
* 返回:String
* 作者:luoc
* 日期:2005-6-22
**/
publicstaticString getElementValue(Element element)
{
NodeList nl=element.getChildNodes();
for(inti=0;i
{
if(nl.item(i).getNodeType()==Node.TEXT_NODE)//是一个Text Node
{
logger.debug(element.getNodeName()+" has a Text Node.");
returnelement.getFirstChild().getNodeValue();
}
}
logger.error(element.getNodeName()+" hasn't a Text Node.");
returnnull;
}
/**
* 方法名称:getElementAttr
* 方法功能:获取指定Element的属性attr的值
* 参数说明:@param element
* 参数说明:@param attr
* 参数说明:@return
* 返回:String
* 作者:luoc
* 日期:2005-6-22
**/
publicstaticString getElementAttr(Element element,String attr)
{
returnelement.getAttribute(attr);
}
/**
* 方法名称:setElementValue
* 方法功能:设置指定Element的值
* 参数说明:@param element
* 参数说明:@param val
* 返回:void
* 作者:luoc
* 日期:2005-6-22
**/
publicstaticvoidsetElementValue(Element element,String val)
{
Node node=element.getOwnerDocument().createTextNode(val);
NodeList nl=element.getChildNodes();
for(inti=0;i
{
Node nd=nl.item(i);
if(nd.getNodeType()==Node.TEXT_NODE)//是一个Text Node
{
nd.setNodeValue(val);
logger.debug("modify "+element.getNodeName()+"'s node value succe.");
return;
}
}
logger.debug("new "+element.getNodeName()+"'s node value succe.");
element.appendChild(node);
}
/**
* 方法名称:setElementAttr
* 方法功能:设置结点Element的属性
* 参数说明:@param element
* 参数说明:@param attr
* 参数说明:@param attrVal
* 返回:void
* 作者:luoc
* 日期:2005-6-22
**/
publicstaticvoidsetElementAttr(Element element,
String attr,String attrVal)
{
element.setAttribute(attr,attrVal);
}
/**
* 方法名称:addElement
* 方法功能:在parent下增加结点child
* 参数说明:@param parent
* 参数说明:@param child
* 返回:void
* 作者:luoc
* 日期:2005-6-22
**/
publicstaticvoidaddElement(Element parent,Element child)
{
parent.appendChild(child);
}
/**
* 方法名称:addElement
* 方法功能:在parent下增加字符串tagName生成的结点
* 参数说明:@param parent
* 参数说明:@param tagName
* 返回:void
* 作者:luoc
* 日期:2005-6-22
**/
publicstaticvoidaddElement(Element parent,String tagName)
{
Document doc=parent.getOwnerDocument();
Element child=doc.createElement(tagName);
parent.appendChild(child);
}
/**
* 方法名称:addElement
* 方法功能:在parent下增加tagName的Text结点,且值为text
* 参数说明:@param parent
* 参数说明:@param tagName
* 参数说明:@param text
* 返回:void
* 作者:luoc
* 日期:2005-6-22
**/
publicstaticvoidaddElement(Element parent,String tagName,String text)
{
Document doc=parent.getOwnerDocument();
Element child=doc.createElement(tagName);
setElementValue(child,text);
parent.appendChild(child);
}
/**
* 方法名称:removeElement
* 方法功能:将父结点parent下的名称为tagName的结点移除
* 参数说明:@param parent
* 参数说明:@param tagName
* 返回:void
* 作者:luoc
* 日期:2005-6-22
**/
publicstaticvoidremoveElement(Element parent,String tagName)
{
logger.debug("remove "+parent.getNodeName()+"'s children by tagName "+tagName+" begin...");
NodeList nl=parent.getChildNodes();
for(inti=0;i
{
Node nd=nl.item(i);
if(nd.getNodeName().equals(tagName))
{
parent.removeChild(nd);
logger.debug("remove child '"+nd+"' success.");
}
}
logger.debug("remove "+parent.getNodeName()+"'s children by tagName "+tagName+" end.");
}
/*全局变量*/
staticLogger logger=Logger.getLogger("XmlOper");
}
三、新建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
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
XmlCreater.java
用于创建XML文件
/********************************************************************
* 项目名称 :rochoc
* 包名称 :rochoc.xml.oper
* 文件名称 :XmlCreater
* 编写者 :luoc
* 编写日期 :2005-6-22
* 程序功能(类)描述 : 创建DOM并生成XML文件
*
* 程序变更日期 :
* 变更作者 :
* 变更说明 :
********************************************************************/
packagerochoc.xml.oper;
importjava.io.File;
importjavax.xml.parsers.DocumentBuilder;
importjavax.xml.parsers.DocumentBuilderFactory;
importjavax.xml.parsers.ParserConfigurationException;
importjavax.xml.transform.Transformer;
importjavax.xml.transform.TransformerConfigurationException;
importjavax.xml.transform.TransformerException;
importjavax.xml.transform.TransformerFactory;
importjavax.xml.transform.dom.DOMSource;
importjavax.xml.transform.stream.StreamResult;
importorg.apache.log4j.Logger;
importorg.w3c.dom.Document;
importorg.w3c.dom.Element;
/**
* 类名:XmlCreater
* 类描述: 创建DOM并生成XML文件
* 编写者 :luoc
* 编写日期 :2005-6-22
* 主要public成员变量:
* 主要public方法:
**/
publicclassXmlCreater
{
/**
*构造函数说明:
*参数说明:@param path xml文件路径
**/
publicXmlCreater(String path)
{
this.path=path;
init();
}
/**
* 方法名称:init
* 方法功能: 初始化函数
* 参数说明:
* 返回:void
* 作者:luoc
* 日期:2005-6-22
**/
privatevoidinit()
{
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder builder=factory.newDocumentBuilder();
doc=builder.newDocument();//新建DOM
}catch(ParserConfigurationException e)
{
logger.error("Parse DOM builder error:"+e);
}
}
/**
* 方法名称:createRootElement
* 方法功能:创建根结点,并返回
* 参数说明:@param rootTagName
* 返回:Element
* 作者:luoc
* 日期:2005-6-22
**/
publicElement createRootElement(String rootTagName)
{
if(doc.getDocumentElement()==null)
{
logger.debug("create root element '"+rootTagName+"' success.");
Element root=doc.createElement(rootTagName);
doc.appendChild(root);
returnroot;
}
logger.warn("this dom's root element is exist,create fail.");
returndoc.getDocumentElement();
}
/**
* 方法名称:createElement
* 方法功能:在parent结点下增加子结点tagName
* 参数说明:@param parent
* 参数说明:@param tagName
* 返回:Element
* 作者:luoc
* 日期:2005-6-22
**/
publicElement createElement(Element parent,String tagName)
{
Document doc=parent.getOwnerDocument();
Element child=doc.createElement(tagName);
parent.appendChild(child);
returnchild;
}
/**
* 方法名称:createElement
* 方法功能:在parent结点下增加值为value的子结点tabName
* 参数说明:@param parent
* 参数说明:@param tagName
* 参数说明:@param value
* 返回:Element
* 作者:luoc
* 日期:2005-6-22
**/
publicElement createElement(Element parent,String tagName,String value)
{
Document doc=parent.getOwnerDocument();
Element child=doc.createElement(tagName);
XmlOper.setElementValue(child,value);
parent.appendChild(child);
returnchild;
}
/**
* 方法名称:createAttribute
* 方法功能:在parent结点下增加属性
* 参数说明:@param parent
* 参数说明:@param attrName 属性名
* 参数说明:@param attrValue 属性值
* 返回:void
* 作者:luoc
* 日期:2005-6-22
**/
publicvoidcreateAttribute(Element parent,String attrName,String attrValue)
{
XmlOper.setElementAttr(parent,attrName,attrValue);
}
/**
* 方法名称:buildXmlFile
* 方法功能:根据DOM生成XML文件
* 参数说明:
* 返回:void
* 作者:luoc
* 日期:2005-6-22
**/
publicvoidbuildXmlFile()
{
TransformerFactory tfactory=TransformerFactory.newInstance();
try
{
Transformer transformer=tfactory.newTransformer();
DOMSource source=newDOMSource(doc);
logger.debug("New DOMSource success.");
StreamResult result=newStreamResult(newFile(path));
logger.debug("New StreamResult success.");
transformer.setOutputProperty("encoding","GBK");
transformer.transform(source,result);
logger.debug("Build XML File '"+path+"' success.");
}catch(TransformerConfigurationException e)
{
logger.error("Create Transformer error:"+e);
}catch(TransformerException e)
{
logger.error("Transformer XML file error:"+e);
}
}
/**
* @return 返回 doc。
*/
publicDocument getDoc()
{
returndoc;
}
/**
* @param doc 要设置的 doc。
*/
publicvoidsetDoc(Document doc)
{
this.doc = doc;
}
/**
* @return 返回 path。
*/
publicString getPath()
{
returnpath;
}
/**
* @param path 要设置的 path。
*/
publicvoidsetPath(String path)
{
this.path = path;
}
/*全局变量*/
privateLogger logger = Logger.getLogger(getClass().getName());
privateDocument doc=null;//新创建的DOM
privateString path=null;//生成的XML文件绝对路径
}