附件:http://files.cnblogs.com/xe2011/XML_Writer_And_Read.rar
下面这段代码实现了以下功能
数据保存 textBox1的文本,textBox2的文本,窗体的LEFT TOP WIDTH HEIGHT
读取数据 textBox1的文本,textBox2的文本,窗体的LEFT TOP WIDTH HEIGHT
引用XML
using System.Xml;
用XmlTextWriter 创建一个XML结构文件
private void button1_Click(object sender, EventArgs e)
{
XmlTextWriter xml = new XmlTextWriter("WindowsFormsApplicationConfig.xml", Encoding.UTF8);
xml.WriteStartDocument();
xml.WriteStartElement("配置信息"); xml.WriteStartElement("Form1");
xml.WriteElementString("Left", this.Left.ToString());
xml.WriteElementString("Top", this.Top.ToString());
xml.WriteElementString("Width", this.Width.ToString());
xml.WriteElementString("Height", this.Height.ToString());
xml.WriteEndElement(); xml.WriteStartElement("TextBox1");
xml.WriteElementString("Text", textBox1.Text);
xml.WriteEndElement(); xml.WriteStartElement("TextBox2");
xml.WriteElementString("Text", textBox2.Text);
xml.WriteEndElement(); xml.WriteEndElement();
xml.WriteEndDocument();
xml.Close();
}
读取XML文件
private void button2_Click(object sender, EventArgs e)
{ XmlTextReader xml = new XmlTextReader("WindowsFormsApplicationConfig.xml");
while (xml.Read())
{
xml.ReadStartElement("配置信息"); xml.ReadStartElement("Form1");
Left = Convert.ToInt32(xml.ReadElementString("Left"));
Top = Convert.ToInt32(xml.ReadElementString("Top"));
Width = Convert.ToInt32(xml.ReadElementString("Width"));
Height = Convert.ToInt32(xml.ReadElementString("Height"));
xml.ReadEndElement(); xml.ReadStartElement("TextBox1");
textBox1.Text = xml.ReadElementString("Text");
xml.ReadEndElement(); xml.ReadStartElement("TextBox2");
textBox2.Text = xml.ReadElementString("Text");
xml.ReadEndElement(); xml.ReadEndElement();
}
xml.Close();
}
XML文件