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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章