读写XML文件
开发工具VS2010
新建test.xml文件,将xml文件存储目录目录下的调试目录,即与应用程序目录目录下
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