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   <p>
  * 包名称      :rochoc.xml.oper <p>
  * 文件名称    :XmlBuilder   <p>
  * 编写者     :luoc    <p>
  * 编写日期    :2005-6-22    <p>
  * 程序功能(类)描述 : 根据传入的XML文件生成Document和root结点<p>
  *
  * 程序变更日期   :
  * 变更作者    :
  * 变更说明    :
********************************************************************/
package  rochoc.xml.oper;
 
import  java.io.File;
import  java.io.IOException;
 
import  javax.xml.parsers.DocumentBuilder;
import  javax.xml.parsers.DocumentBuilderFactory;
import  javax.xml.parsers.ParserConfigurationException;
 
import  org.apache.log4j.Logger;
import  org.w3c.dom.Document;
import  org.w3c.dom.Element;
import  org.xml.sax.SAXException;
 
/**
  * 类名:XmlBuilder  <p>
  * 类描述:根据传入的XML文件生成Document和root结点 <p>
  * 编写者 :luoc<p>
  * 编写日期 :2005-6-22<p>
  * 主要public成员变量:<p>
  * 主要public方法:   <p>
  **/
 
public  class  XmlBuilder
{
     /**
      *构造函数说明:       <p>
      *参数说明:@param path   <p>
     **/
     public  XmlBuilder(String path)
     {
         this .path=path;
         init();
     }
     
     /**
     * 方法名称:init<p>
     * 方法功能:初始化函数<p>
     * 参数说明: <p>
     * 返回:void <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  void  init()
     {
         buildDocument();
         buildRoot();
     }
     
     /**
     * 方法名称:buildDocument<p>
     * 方法功能:将XML文件生成Document <p>
     * 参数说明: <p>
     * 返回:void <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     private  void  buildDocument()
     {
         DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
         try
         {
             DocumentBuilder builder=factory.newDocumentBuilder();
             logger.debug( "Construct document builder success." );
             doc=builder.parse( new  File(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<p>
     * 方法功能:生成XML的根结点<p>
     * 参数说明: <p>
     * 返回:void <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     private  void  buildRoot()
     {
         root=doc.getDocumentElement();
     }
     
     /**
      * @return 返回 doc。
      */
     public  Document getDoc()
     {
         return  doc;
     }
     /**
      * @param doc 要设置的 doc。
      */
     public  void  setDoc(Document doc)
     {
         this .doc = doc;
     }
     /**
      * @return 返回 path。
      */
     public  String getPath()
     {
         return  path;
     }
     /**
      * @param path 要设置的 path。
      */
     public  void  setPath(String path)
     {
         this .path = path;
     }
     /**
      * @return 返回 root。
      */
     public  Element getRoot()
     {
         return  root;
     }
     /**
      * @param root 要设置的 root。
      */
     public  void  setRoot(Element root)
     {
         this .root = root;
     }
     /*全局变量*/
     private  String path= null ; //xml文件路径
     private  Document doc= null ; //xml文件对应的document
     private  Element root= null ; //xml文件的根结点
     private  Logger 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   <p>
  * 包名称      :rochoc.xml.oper <p>
  * 文件名称    :XmlOper   <p>
  * 编写者     :luoc    <p>
  * 编写日期    :2005-6-22    <p>
  * 程序功能(类)描述 : 对XML进行读写操作      <p>
  *
  * 程序变更日期   :
  * 变更作者    :
  * 变更说明    :
********************************************************************/
package  rochoc.xml.oper;
 
import  java.util.ArrayList;
 
import  org.apache.log4j.Logger;
import  org.w3c.dom.Document;
import  org.w3c.dom.Element;
import  org.w3c.dom.Node;
import  org.w3c.dom.NodeList;
 
/**
  * 类名:XmlOper  <p>
  * 类描述:对XML文件进行读写操作,均为静态函数 <p>
  * 编写者 :luoc<p>
  * 编写日期 :2005-6-22<p>
  * 主要public成员变量:<p>
  * 主要public方法:   <p>
  **/
 
public  class  XmlOper
{
     /**
      *构造函数说明:       <p>
      *参数说明:   <p>
     **/
     private  XmlOper()
     {       
     }
     
     /**
     * 方法名称:getNodeList<p>
     * 方法功能:获取父结点parent的所有子结点<p>
     * 参数说明:@param parent
     * 参数说明:@return <p>
     * 返回:NodeList <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  static  NodeList getNodeList(Element parent)
     {
         return  parent.getChildNodes();
     }
     
     /**
     * 方法名称:getElementsByName<p>
     * 方法功能:在父结点中查询指定名称的结点集            <p>
     * 参数说明:@param parent
     * 参数说明:@param name
     * 参数说明:@return <p>
     * 返回:Element[] <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  static  Element [] getElementsByName(Element parent,String name)
     {
         ArrayList resList= new  ArrayList();
         NodeList nl=getNodeList(parent);
         for ( int  i= 0 ;i<nl.getLength();i++)
         {
             Node nd=nl.item(i);
             if (nd.getNodeName().equals(name))
             {
                 resList.add(nd);
             }
         }
         Element [] res= new  Element [resList.size()];
         for ( int  i= 0 ;i<resList.size();i++)
         {
             res[ 0 ]=(Element)resList.get(i);
         }       
         logger.debug(parent.getNodeName()+ "'s children of " +name+
                 "'s num:" +res.length);
         return  res;
     }
     
     /**
     * 方法名称:getElementName<p>
     * 方法功能:获取指定Element的名称            <p>
     * 参数说明:@param element
     * 参数说明:@return <p>
     * 返回:String <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  static  String getElementName(Element element)
     {
         return  element.getNodeName();
     }
     
     /**
     * 方法名称:getElementValue<p>
     * 方法功能:获取指定Element的值<p>
     * 参数说明:@param element
     * 参数说明:@return <p>
     * 返回:String <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  static  String getElementValue(Element element)
     {
         NodeList nl=element.getChildNodes();
         for ( int  i= 0 ;i<nl.getLength();i++)
         {
             if (nl.item(i).getNodeType()==Node.TEXT_NODE) //是一个Text Node
             {           
                 logger.debug(element.getNodeName()+ " has a Text Node." );
                 return  element.getFirstChild().getNodeValue();
             }
         }  
         logger.error(element.getNodeName()+ " hasn't a Text Node." );
         return  null ;
     }
     
     /**
     * 方法名称:getElementAttr<p>
     * 方法功能:获取指定Element的属性attr的值            <p>
     * 参数说明:@param element
     * 参数说明:@param attr
     * 参数说明:@return <p>
     * 返回:String <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  static  String getElementAttr(Element element,String attr)
     {
         return  element.getAttribute(attr);
     }
     
     /**
     * 方法名称:setElementValue<p>
     * 方法功能:设置指定Element的值            <p>
     * 参数说明:@param element
     * 参数说明:@param val <p>
     * 返回:void <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  static  void  setElementValue(Element element,String val)
     {
         Node node=element.getOwnerDocument().createTextNode(val);
         NodeList nl=element.getChildNodes();
         for ( int  i= 0 ;i<nl.getLength();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<p>
     * 方法功能:设置结点Element的属性<p>
     * 参数说明:@param element
     * 参数说明:@param attr
     * 参数说明:@param attrVal <p>
     * 返回:void <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  static  void  setElementAttr(Element element,
             String attr,String attrVal)
     {
         element.setAttribute(attr,attrVal);
     }
     
     
     /**
     * 方法名称:addElement<p>
     * 方法功能:在parent下增加结点child<p>
     * 参数说明:@param parent
     * 参数说明:@param child <p>
     * 返回:void <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  static  void  addElement(Element parent,Element child)
     {
         parent.appendChild(child);
     }
     
     /**
     * 方法名称:addElement<p>
     * 方法功能:在parent下增加字符串tagName生成的结点<p>
     * 参数说明:@param parent
     * 参数说明:@param tagName <p>
     * 返回:void <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  static  void  addElement(Element parent,String tagName)
     {       
         Document doc=parent.getOwnerDocument();
         Element child=doc.createElement(tagName);
         parent.appendChild(child);
     }
     
     /**
     * 方法名称:addElement<p>
     * 方法功能:在parent下增加tagName的Text结点,且值为text<p>
     * 参数说明:@param parent
     * 参数说明:@param tagName
     * 参数说明:@param text <p>
     * 返回:void <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  static  void  addElement(Element parent,String tagName,String text)
     {
         Document doc=parent.getOwnerDocument();
         Element child=doc.createElement(tagName);
         setElementValue(child,text);
         parent.appendChild(child);
     }
     
     /**
     * 方法名称:removeElement<p>
     * 方法功能:将父结点parent下的名称为tagName的结点移除<p>
     * 参数说明:@param parent
     * 参数说明:@param tagName <p>
     * 返回:void <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  static  void  removeElement(Element parent,String tagName)
     {
         logger.debug( "remove " +parent.getNodeName()+ "'s children by tagName " +tagName+ " begin..." );
         NodeList nl=parent.getChildNodes();
         for ( int  i= 0 ;i<nl.getLength();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." );
     }
     
     
     /*全局变量*/   
     static  Logger 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   <p>
  * 包名称      :rochoc.xml.oper <p>
  * 文件名称    :XmlCreater   <p>
  * 编写者     :luoc    <p>
  * 编写日期    :2005-6-22    <p>
  * 程序功能(类)描述 : 创建DOM并生成XML文件      <p>
  *
  * 程序变更日期   :
  * 变更作者    :
  * 变更说明    :
********************************************************************/
package  rochoc.xml.oper;
 
import  java.io.File;
 
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.TransformerException;
import  javax.xml.transform.TransformerFactory;
import  javax.xml.transform.dom.DOMSource;
import  javax.xml.transform.stream.StreamResult;
 
import  org.apache.log4j.Logger;
import  org.w3c.dom.Document;
import  org.w3c.dom.Element;
 
/**
  * 类名:XmlCreater  <p>
  * 类描述: 创建DOM并生成XML文件<p>
  * 编写者 :luoc<p>
  * 编写日期 :2005-6-22<p>
  * 主要public成员变量:<p>
  * 主要public方法:   <p>
  **/
 
public  class  XmlCreater
{
     /**
      *构造函数说明:       <p>
      *参数说明:@param path  xml文件路径 <p>
     **/
     public  XmlCreater(String path)
     {
         this .path=path;
         init();
     }
     
     /**
     * 方法名称:init<p>
     * 方法功能: 初始化函数           <p>
     * 参数说明: <p>
     * 返回:void <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     private  void  init()
     {
         DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
         try
         {
             DocumentBuilder builder=factory.newDocumentBuilder();
             doc=builder.newDocument(); //新建DOM
         } catch (ParserConfigurationException e)
         {
             logger.error( "Parse DOM builder error:" +e);
         }
     }
     
     /**
     * 方法名称:createRootElement<p>
     * 方法功能:创建根结点,并返回            <p>
     * 参数说明:@param rootTagName <p>
     * 返回:Element <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  Element createRootElement(String rootTagName)
     {    
         if (doc.getDocumentElement()== null )
         {
             logger.debug( "create root element '" +rootTagName+ "' success." );
             Element root=doc.createElement(rootTagName);
             doc.appendChild(root);
             return  root;
         }
         logger.warn( "this dom's root element is exist,create fail." );
         return  doc.getDocumentElement();
     }
     
     /**
     * 方法名称:createElement<p>
     * 方法功能:在parent结点下增加子结点tagName<p>
     * 参数说明:@param parent
     * 参数说明:@param tagName <p>
     * 返回:Element <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  Element createElement(Element parent,String tagName)
     {
         Document doc=parent.getOwnerDocument();
         Element child=doc.createElement(tagName);
         parent.appendChild(child);       
         return  child;
     }
     
     /**
     * 方法名称:createElement<p>
     * 方法功能:在parent结点下增加值为value的子结点tabName<p>
     * 参数说明:@param parent
     * 参数说明:@param tagName
     * 参数说明:@param value <p>
     * 返回:Element <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  Element createElement(Element parent,String tagName,String value)
     {
         Document doc=parent.getOwnerDocument();
         Element child=doc.createElement(tagName);
         XmlOper.setElementValue(child,value);
         parent.appendChild(child);
         return  child;
     }
     
     /**
     * 方法名称:createAttribute<p>
     * 方法功能:在parent结点下增加属性 <p>
     * 参数说明:@param parent
     * 参数说明:@param attrName 属性名
     * 参数说明:@param attrValue 属性值<p>
     * 返回:void <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  void  createAttribute(Element parent,String attrName,String attrValue)
     {
         XmlOper.setElementAttr(parent,attrName,attrValue);       
     }
     
     /**
     * 方法名称:buildXmlFile<p>
     * 方法功能:根据DOM生成XML文件<p>
     * 参数说明: <p>
     * 返回:void <p>
     * 作者:luoc
     * 日期:2005-6-22
     **/
     public  void  buildXmlFile()
     {
         TransformerFactory tfactory=TransformerFactory.newInstance();
         try
         {
             Transformer transformer=tfactory.newTransformer();
             DOMSource source= new  DOMSource(doc);
             logger.debug( "New DOMSource success." );
             StreamResult result= new  StreamResult( new  File(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。
      */
     public  Document getDoc()
     {
         return  doc;
     }
     /**
      * @param doc 要设置的 doc。
      */
     public  void  setDoc(Document doc)
     {
         this .doc = doc;
     }
     /**
      * @return 返回 path。
      */
     public  String getPath()
     {
         return  path;
     }
     /**
      * @param path 要设置的 path。
      */
     public  void  setPath(String path)
     {
         this .path = path;
     }
     /*全局变量*/
     private  Logger logger = Logger.getLogger(getClass().getName());
     private  Document doc= null ; //新创建的DOM
     private  String path= null ; //生成的XML文件绝对路径
}
原文转自: http://www.cnblogs.com/ITEagle/archive/2010/03/03/1677431.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值