代码:
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 }
读取:
//产生读取器。
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();
}
}