读写XML文件
开发工具VS2010
新建test.xml文件,并将xml文件放在bin目录下的Debug目录,即与应用程序放在同一目录下
XML文件样式
<?xml version="1.0" encoding="utf-8"?> <main> <user>admin</user> <psw>456</psw> </main>
窗体
读取
XmlDocument xml = new XmlDocument(); xml.Load(Application.StartupPath+"//"+"test.xml");//加载xml文件 XmlNode xn = xml.DocumentElement; tb_user.Text = xn["user"].InnerText; tb_psw.Text = xn["psw"].InnerText; label1.Text = xn["user"].InnerText +" "+ xn["psw"].InnerText;
窗体效果
写入
XmlDocument xml = new XmlDocument(); xml.Load(Application.StartupPath + "//" + "test.xml");//加载xml文件 XmlNode xn = xml.DocumentElement; xn["user"].InnerText = tb_user.Text; xn["psw"].InnerText = tb_psw.Text; xml.Save(Application.StartupPath + "//" + "test.xml");//保存xml文件 label1.Text = xn["user"].InnerText + " " + xn["psw"].InnerText;
窗体效果
完整代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml; namespace RwXml { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btn_r_Click(object sender, EventArgs e) { XmlDocument xml = new XmlDocument(); xml.Load(Application.StartupPath+"//"+"test.xml");//加载xml文件 XmlNode xn = xml.DocumentElement; tb_user.Text = xn["user"].InnerText; tb_psw.Text = xn["psw"].InnerText; label1.Text = xn["user"].InnerText +" "+ xn["psw"].InnerText; } private void btn_w_Click(object sender, EventArgs e) { XmlDocument xml = new XmlDocument(); xml.Load(Application.StartupPath + "//" + "test.xml");//加载xml文件 XmlNode xn = xml.DocumentElement; xn["user"].InnerText = tb_user.Text; xn["psw"].InnerText = tb_psw.Text; xml.Save(Application.StartupPath + "//" + "test.xml");//保存xml文件 label1.Text = xn["user"].InnerText + " " + xn["psw"].InnerText; } } }
注:C#对xml文件进行操作,需要引用System.Xml
微信公众号 weisico-com
转载请注明:微思考学习网-关注技术,分享知识 >> c# winform读写XML文件