.net操作xml文件(新增.修改,刪除,讀取)

今天有個需求需要操作xml節點.突然見遺忘了許多.上網看了些資料.才整出來.腦袋真不夠用.在這裏把我找到的資料共享一下.方便以後使用.本文屬於網摘/
1 一、簡單介紹
2 using System.Xml;
3 //初始化一個xml實例
4 XmlDocument xml=new XmlDocument();
5 //導入指定xml文件
6 xml.Load(path);
7 xml.Load(HttpContext.Current.Server.MapPath("~/file/bookstore.xml"));
8 //指定一個節點
9 XmlNode root=xml.SelectSingleNode("/root");
10 //獲取節點下所有直接子節點
11 XmlNodeList childlist=root.ChildNodes;
12 //判斷該節點下是否有子節點
13 root.HasChildNodes;
14 //獲取同名同級節點集合
15 XmlNodeList nodelist=xml.SelectNodes("/Root/News");
16 //生成一個新節點
17 XmlElement node=xml.createElement_x("News");
18 //將節點加到指定節點下,作爲其子節點
19 root.AppendChild(node);
20 //將節點加到指定節點下某個子節點前
21 root.InsertBefore(node,root.ChildeNodes[i]);
22 //爲指定節點的新建屬性並賦值
23 node.SetAttribute("id","11111");
24 //爲指定節點添加子節點
25 root.AppendChild(node);
26 //獲取指定節點的指定屬性值
27 string id=node.Attributes["id"].Value;
28 //獲取指定節點中的文本
29 string content=node.InnerText;
30 //保存XML文件
31 string path=Server.MapPath("~/file/bookstore.xml");
32 xml.Save(path);
33 //or use :xml.Save(HttpContext.Current.Server.MapPath("~/file/bookstore.xml")); 
34 二、具體實例
35 在C#.net中如何操作XML
36 需要添加的命名空間:
37 using System.Xml;
38 定義幾個公共對象:
39 XmlDocument xmldoc ;
40 XmlNode xmlnode ;
41 XmlElement xmlelem ;
42 1,創建到服務器同名目錄下的xml文件:
43 
44 方法一:
45 xmldoc = new XmlDocument ( ) ;
46 //加入XML的聲明段落,<?xml version="1.0" encoding="gb2312"?>
47 XmlDeclaration xmldecl;
48 xmldecl = xmldoc.CreateXmlDeclaration("1.0","gb2312",null);
49 xmldoc.AppendChild ( xmldecl);
50 //加入一個根元素
51 xmlelem = xmldoc.createElement_x ( "" , "Employees" , "" ) ;
52 xmldoc.AppendChild ( xmlelem ) ;
53 //加入另外一個元素
54 for(int i=1;i<3;i++)
55 {
56 XmlNode root=xmldoc.SelectSingleNode("Employees");//查找<Employees> 
57 XmlElement xe1=xmldoc.createElement_x("Node");//創建一個<Node>節點 
58 xe1.SetAttribute("genre","李贊紅");//設置該節點genre屬性 
59 xe1.SetAttribute("ISBN","2-3631-4");//設置該節點ISBN屬性
60 XmlElement xesub1=xmldoc.createElement_x("title"); 
61 xesub1.InnerText="CS從入門到精通";//設置文本節點 
62 xe1.AppendChild(xesub1);//添加到<Node>節點中 
63 XmlElement xesub2=xmldoc.createElement_x("author"); 
64 xesub2.InnerText="候捷"65 xe1.AppendChild(xesub2); 
66 XmlElement xesub3=xmldoc.createElement_x("price"); 
67 xesub3.InnerText="58.3"68 xe1.AppendChild(xesub3);
69 root.AppendChild(xe1);//添加到<Employees>節點中 
70 }
71 //保存創建好的XML文檔
72 xmldoc.Save ( Server.MapPath("data.xml") ) ;
73//////////////////////////////////////////////////////////////////////////////////////
74 結果:在同名目錄下生成了名爲data.xml的文件,內容如下,
75 <?xml version="1.0" encoding="gb2312"?>
76 <Employees>
77 <Node genre="李贊紅" ISBN="2-3631-4">
78 <title>CS從入門到精通</title>
79 <author>候捷</author>
80 <price>58.3</price>
81 </Node>
82 <Node genre="李贊紅" ISBN="2-3631-4">
83 <title>CS從入門到精通</title>
84 <author>候捷</author>
85 <price>58.3</price>
86 </Node>
87 </Employees>
88 
89 方法二:
90 XmlTextWriter xmlWriter;
91 string strFilename = Server.MapPath("data1.xml") ;
92 xmlWriter = new XmlTextWriter(strFilename,Encoding.Default);//創建一個xml文檔
93 xmlWriter.Formatting = Formatting.Indented;
94 xmlWriter.WriteStartDocument();
95 xmlWriter.WriteStartElement("Employees");
96 xmlWriter.WriteStartElement("Node");
97 xmlWriter.WriteAttributeString("genre","李贊紅");
98 xmlWriter.WriteAttributeString("ISBN","2-3631-4");
99 xmlWriter.WriteStartElement("title");
100 xmlWriter.WriteString("CS從入門到精通");
101 xmlWriter.WriteEndElement();
102 xmlWriter.WriteStartElement("author");
103 xmlWriter.WriteString("候捷");
104 xmlWriter.WriteEndElement();
105 xmlWriter.WriteStartElement("price");
106 xmlWriter.WriteString("58.3");
107 xmlWriter.WriteEndElement();
108 xmlWriter.WriteEndElement();
109 xmlWriter.Close();
110//////////////////////////////////////////////////////////////////////////////////////
111 結果:
112 <?xml version="1.0" encoding="gb2312"?>
113 <Employees>
114 <Node genre="李贊紅" ISBN="2-3631-4">
115 <title>CS從入門到精通</title>
116 <author>候捷</author>
117 <price>58.3</price>
118 </Node>
119 </Employees>
120 2,添加一個結點:
121 XmlDocument xmlDoc=new XmlDocument(); 
122 xmlDoc.Load(Server.MapPath("data.xml")); 
123 XmlNode root=xmlDoc.SelectSingleNode("Employees");//查找<Employees> 
124 XmlElement xe1=xmlDoc.createElement_x("Node");//創建一個<Node>節點 
125 xe1.SetAttribute("genre","張三");//設置該節點genre屬性 
126 xe1.SetAttribute("ISBN","1-1111-1");//設置該節點ISBN屬性
127 XmlElement xesub1=xmlDoc.createElement_x("title"); 
128 xesub1.InnerText="C#入門幫助";//設置文本節點 
129 xe1.AppendChild(xesub1);//添加到<Node>節點中 
130 XmlElement xesub2=xmlDoc.createElement_x("author"); 
131 xesub2.InnerText="高手"132 xe1.AppendChild(xesub2); 
133 XmlElement xesub3=xmlDoc.createElement_x("price"); 
134 xesub3.InnerText="158.3"135 xe1.AppendChild(xesub3);
136 root.AppendChild(xe1);//添加到<Employees>節點中 
137 xmlDoc.Save ( Server.MapPath("data.xml") );
138//////////////////////////////////////////////////////////////////////////////////////
139 結果:在xml原有的內容裏添加了一個結點,內容如下,
140 <?xml version="1.0" encoding="gb2312"?>
141 <Employees>
142 <Node genre="李贊紅" ISBN="2-3631-4">
143 <title>CS從入門到精通</title>
144 <author>候捷</author>
145 <price>58.3</price>
146 </Node>
147 <Node genre="李贊紅" ISBN="2-3631-4">
148 <title>CS從入門到精通</title>
149 <author>候捷</author>
150 <price>58.3</price>
151 </Node>
152 <Node genre="張三" ISBN="1-1111-1">
153 <title>C#入門幫助</title>
154 <author>高手</author>
155 <price>158.3</price>
156 </Node>
157 </Employees>
158 3,修改結點的值(屬性和子結點):
159 XmlDocument xmlDoc=new XmlDocument(); 
160 xmlDoc.Load( Server.MapPath("data.xml") );
161 XmlNodeList nodeList=xmlDoc.SelectSingleNode("Employees").ChildNodes;//獲取Employees節點的所有子節點
162 foreach(XmlNode xn in nodeList)//遍歷所有子節點 
163 { 
164 XmlElement xe=(XmlElement)xn;//將子節點類型轉換爲XmlElement類型 
165 if(xe.GetAttribute("genre")=="張三")//如果genre屬性值爲“張三” 
166 { 
167 xe.SetAttribute("genre","update張三");//則修改該屬性爲“update張三”
168 XmlNodeList nls=xe.ChildNodes;//繼續獲取xe子節點的所有子節點 
169 foreach(XmlNode xn1 in nls)//遍歷 
170 { 
171 XmlElement xe2=(XmlElement)xn1;//轉換類型 
172 if(xe2.Name=="author")//如果找到 
173 { 
174 xe2.InnerText="亞勝";//則修改
175 } 
176 } 
177 } 
178 } 
179 xmlDoc.Save( Server.MapPath("data.xml") );//保存。
180//////////////////////////////////////////////////////////////////////////////////////
181 結果:將原來的所有結點的信息都修改了,xml的內容如下,
182 <?xml version="1.0" encoding="gb2312"?>
183 <Employees>
184 <Node genre="李贊紅" ISBN="2-3631-4">
185 <title>CS從入門到精通</title>
186 <author>候捷</author>
187 <price>58.3</price>
188 </Node>
189 <Node genre="李贊紅" ISBN="2-3631-4">
190 <title>CS從入門到精通</title>
191 <author>候捷</author>
192 <price>58.3</price>
193 </Node>
194 <Node genre="update張三" ISBN="1-1111-1">
195 <title>C#入門幫助</title>
196 <author>亞勝</author>
197 <price>158.3</price>
198 </Node>
199 </Employees>
200 4,修改結點(添加結點的屬性和添加結點的自結點):
201 XmlDocument xmlDoc=new XmlDocument(); 
202 xmlDoc.Load( Server.MapPath("data.xml") );
203 XmlNodeList nodeList=xmlDoc.SelectSingleNode("Employees").ChildNodes;//獲取Employees節點的所有子節點
204 foreach(XmlNode xn in nodeList) 
205 { 
206 XmlElement xe=(XmlElement)xn; 
207 xe.SetAttribute("test","111111");
208 XmlElement xesub=xmlDoc.createElement_x("flag"); 
209 xesub.InnerText="1"210 xe.AppendChild(xesub); 
211 } 
212 xmlDoc.Save( Server.MapPath("data.xml") );
213//////////////////////////////////////////////////////////////////////////////////////
214 結果:每個結點的屬性都添加了一個,子結點也添加了一個,內容如下,
215 <?xml version="1.0" encoding="gb2312"?>
216 <Employees>
217 <Node genre="李贊紅" ISBN="2-3631-4" test="111111">
218 <title>CS從入門到精通</title>
219 <author>候捷</author>
220 <price>58.3</price>
221 <flag>1</flag>
222 </Node>
223 <Node genre="李贊紅" ISBN="2-3631-4" test="111111">
224 <title>CS從入門到精通</title>
225 <author>候捷</author>
226 <price>58.3</price>
227 <flag>1</flag>
228 </Node>
229 <Node genre="update張三" ISBN="1-1111-1" test="111111">
230 <title>C#入門幫助</title>
231 <author>亞勝</author>
232 <price>158.3</price>
233 <flag>1</flag>
234 </Node>
235 </Employees>
236 5,刪除結點中的某一個屬性:
237 XmlDocument xmlDoc=new XmlDocument(); 
238 xmlDoc.Load( Server.MapPath("data.xml") ); 
239 XmlNodeList xnl=xmlDoc.SelectSingleNode("Employees").ChildNodes; 
240 foreach(XmlNode xn in xnl) 
241 { 
242 XmlElement xe=(XmlElement)xn; 
243 xe.RemoveAttribute("genre");//刪除genre屬性
244 XmlNodeList nls=xe.ChildNodes;//繼續獲取xe子節點的所有子節點 
245 foreach(XmlNode xn1 in nls)//遍歷 
246 { 
247 XmlElement xe2=(XmlElement)xn1;//轉換類型 
248 if(xe2.Name=="flag")//如果找到 
249 { 
250 xe.RemoveChild(xe2);//則刪除
251 } 
252 } 
253 } 
254 xmlDoc.Save( Server.MapPath("data.xml") );
255//////////////////////////////////////////////////////////////////////////////////////]
256 結果:刪除了結點的一個屬性和結點的一個子結點,內容如下,
257 <?xml version="1.0" encoding="gb2312"?>
258 <Employees>
259 <Node ISBN="2-3631-4" test="111111">
260 <title>CS從入門到精通</title>
261 <author>候捷</author>
262 <price>58.3</price>
263 </Node>
264 <Node ISBN="2-3631-4" test="111111">
265 <title>CS從入門到精通</title>
266 <author>候捷</author>
267 <price>58.3</price>
268 </Node>
269 <Node ISBN="1-1111-1" test="111111">
270 <title>C#入門幫助</title>
271 <author>亞勝</author>
272 <price>158.3</price>
273 </Node>
274 </Employees>
275 6,刪除結點:
276 XmlDocument xmlDoc=new XmlDocument(); 
277 xmlDoc.Load( Server.MapPath("data.xml") ); 
278 XmlNode root=xmlDoc.SelectSingleNode("Employees");
279 XmlNodeList xnl=xmlDoc.SelectSingleNode("Employees").ChildNodes; 
280 for(int i=0;i<xnl.Count;i++)
281 {
282 XmlElement xe=(XmlElement)xnl.Item(i); 
283 if(xe.GetAttribute("genre")=="張三"284 { 
285 root.RemoveChild(xe);
286 if(i<xnl.Count)i=i-1;
287 } 
288 }
289 xmlDoc.Save( Server.MapPath("data.xml") );
290//////////////////////////////////////////////////////////////////////////////////////]
291 結果:刪除了符合條件的所有結點,原來的內容:
292 <?xml version="1.0" encoding="gb2312"?>
293 <Employees>
294 <Node genre="李贊紅" ISBN="2-3631-4">
295 <title>CS從入門到精通</title>
296 <author>候捷</author>
297 <price>58.3</price>
298 </Node>
299 <Node genre="李贊紅" ISBN="2-3631-4">
300 <title>CS從入門到精通</title>
301 <author>候捷</author>
302 <price>58.3</price>
303 </Node>
304 <Node genre="張三" ISBN="1-1111-1">
305 <title>C#入門幫助</title>
306 <author>高手</author>
307 <price>158.3</price>
308 </Node>
309 <Node genre="張三" ISBN="1-1111-1">
310 <title>C#入門幫助</title>
311 <author>高手</author>
312 <price>158.3</price>
313 </Node>
314 </Employees>
315 刪除後的內容:
316 <?xml version="1.0" encoding="gb2312"?>
317 <Employees>
318 <Node genre="李贊紅" ISBN="2-3631-4">
319 <title>CS從入門到精通</title>
320 <author>候捷</author>
321 <price>58.3</price>
322 </Node>
323 <Node genre="李贊紅" ISBN="2-3631-4">
324 <title>CS從入門到精通</title>
325 <author>候捷</author>
326 <price>58.3</price>
327 </Node>
328 </Employees>
329 7,按照文本文件讀取xml
330 System.IO.StreamReader myFile =new 
331 System.IO.StreamReader(Server.MapPath("data.xml"),System.Text.Encoding.Default);
332 //注意System.Text.Encoding.Default
333 string myString = myFile.ReadToEnd();//myString是讀出的字符串
334 myFile.Close();
335 
336 三、高級應用 
337 
338 <aaa>
339 <bb>something</bb>
340 <cc>something</cc>
341 </aaa>
342 
343 <aaa>
344 <add key="123" value="321"/>
345 </aaa>
346 
347 DS.ReadXml("your xmlfile name");
348 Container.DataItem("bb");
349 Container.DataItem("cc");
350 DS.ReadXmlSchema("your xmlfile name");
351 
352 
353 <aaa>
354 <add key="123" value="321"/>
355 </aaa>
356 如果我要找到123然後取到321應該怎麼寫呢?
357 
358 using System.XML;
359 XmlDataDocument xmlDoc = new System.Xml.XmlDataDocument();
360 xmlDoc.Load(@"c:\Config.xml");
361 XmlElement elem = xmlDoc.GetElementById("add");
362 string str = elem.Attributes["value"].Value
363 
364 
365 
366 --------------------------------------------------------------------
367 <?xml version="1.0" encoding="utf-8" ?>
368 <configuration>
369 <appSettings>
370 <ConnectionString>Data Source=yf; user id=ctm_dbo;password=123</ConnectionString> 
371 </appSettings>
372 </configuration>
373 --------------------------------------------------------------------------
374 XmlDocument doc = new XmlDocument();
375 doc.Load(strXmlName);
376 
377 XmlNode node=doc.SelectSingleNode("/configuration/appSettings/ConnectionString");
378 if(node!=null)
379 {
380 string k1=node.Value; //null
381 string k2=node.InnerText;//Data Source=yf; user id=ctm_dbo;password=123
382 string k3=node.InnerXml;//Data Source=yf; user id=ctm_dbo;password=123
383 node=null;
384 }
385 
386 ********************************************************************
387 <?xml version="1.0" encoding="utf-8" ?>
388 <configuration>
389 <appSettings>
390 <add key="ConnectionString" value="Data Source=yf; user id=ctm_dbo;password=123" /> 
391 </appSettings>
392 </configuration>
393 **--------------------------------------------------------------------**
394 XmlNode node=doc.SelectSingleNode("/configuration/appSettings/add");
395 if(node!=null)
396 {
397 string k=node.Attributes["key"].Value;
398 string v=node.Attributes["value"].Value;
399 node=null;
400 }
401 *--------------------------------------------------------------------*
402 XmlNode node=doc.SelectSingleNode("/configuration/appSettings/add");
403 if(node!=null)
404 {
405 XmlNodeReader nr=new XmlNodeReader(node);
406 nr.MoveToContent();
407 //檢查當前節點是否是內容節點。如果此節點不是內容節點,則讀取器向前跳至下一個內容節點或文件結尾。
408 nr.MoveToAttribute("value");
409 string s=nr.Value;
410 node=null;
411 }
發佈了2 篇原創文章 · 獲贊 7 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章