代码:
1 //创建容器。 2 XmlDocument doc = new XmlDocument(); 3 4 //将空的文档加载到XNL文件。 5 6 doc.LoadXml("<A></A>"); 7 8 //将找到的根节点进行存储。 9 10 XmlNode root = doc.SelectSingleNode("A"); 11 12 //创建相应的元素。 13 14 XmlElement B = doc.CreateElement("B"); 15 16 XmlElement C = doc.CreateElement("C"); 17 18 XmlElement D = doc.CreateElement("D"); 19 20 XmlElement E = doc.CreateElement("E"); 21 22 //赋值。 23 24 C.InnerText = textBox1.Text.ToString().Trim(); 25 26 D.InnerText = textBox2.Text.ToString().Trim(); 27 28 E.InnerText = textBox3.Text.ToString().Trim(); 29 30 //相应的添加节点 31 32 B.AppendChild(C); 33 34 B.AppendChild(D); 35 36 root.AppendChild(B); 37 38 root.AppendChild(E); 39 40 //进行保存。位置在EXE路径下。 41 42 try 43 44 { 45 46 doc.Save("setting.xml"); 47 48 MessageBox.Show("写入成功!"); 49 50 } 51 52 catch 53 54 { 55 56 MessageBox.Show("写入错误!"); 57 58 }
读取:
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 |
//产生读取器。 XmlTextReader read; //判断是否存在外部xml,如存在则读取外部的资源,如不存在则读取内部资源。 if
(File.Exists( "setting.xml" )) { read = new
XmlTextReader( "setting.xml" ); } else { Assembly asm = Assembly.GetExecutingAssembly(); Stream sm = asm.GetManifestResourceStream( "Tetris.setting.xml" ); read = new
XmlTextReader(sm); } //key作为存储器进行信息存放。 string
key = "" ; try { //循环进行读取。 while
(read.Read()) { if
(read.Name == "C" ) { key = read.ReadElementString().Trim(); textBox1.Text = key.ToString().Trim(); } else
if (read.Name == "D" ) { key = read.ReadElementString().Trim(); textBox2.Text = key.ToString().Trim(); } else
if (read.Name == "E" ) { key = read.ReadElementString().Trim(); textBox3.Text = key.ToString().Trim(); } } } //异常处理。 catch
(Exception ex) { MessageBox.Show(ex.ToString()); } //关闭读取器。 finally { if
(read != null ) { read.Close(); } } |
C# 创建、读取 .xml文件的简单实例,布布扣,bubuko.com
原文:http://www.cnblogs.com/ATS-MES/p/3607204.html