users.xml 存放路径: 当前C#工程目录下的debug文件夹中

<?xml version="1.0" encoding="gb2312"?>
<root>
  <user>
    <username>meteorWJ</username>
    <password>123</password>
  </user>
  <user>
    <username>eleven</username>
    <password>111</password>
  </user>
</root>

Windows 窗体程序

public partial class Form1 : Form
    {
        private DataSet ds = new DataSet();
        public Form1()
        {
            InitializeComponent();
        }        private void button1_Click(object sender, EventArgs e)
        {
            ds.ReadXml("users.xml");
            bool flag = false;
            foreach (DataTable dt in ds.Tables)
            {
                if (dt.TableName == "user")
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (dr["username"].ToString() == username.Text)
                        {
                            if (dr["password"].ToString() == password.Text)
                            {
                              
                                flag = true;
                            }
                              
                        }                  }
                                                           
                }
            }            if (flag == true)
            {
                dataGrid.DataSource = ds.Tables[0];
            }
            else
            {
                MessageBox.Show("登录信息不正确!");
            }
        }        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("users.xml");
                XmlElement newUser = doc.CreateElement("user");                XmlElement newUsername = doc.CreateElement("username");
                newUsername.InnerText = username.Text;
                newUser.AppendChild(newUsername);
                XmlElement newUserpass = doc.CreateElement("password");
                newUserpass.InnerText = password.Text;
                newUser.AppendChild(newUserpass);
                doc.DocumentElement.AppendChild(newUser);
                doc.Save("user.xml");
                MessageBox.Show("用户"+username.Text+"添加成功!");
            }
            catch (Exception ex)
            {
               MessageBox.Show(ex.Message);            }          
        }
    }

运行效果:

C# 读写XML文件_encoding



users.xml
<?xml versinotallow="1.0" encoding="gb2312"?>
<root>
  <user>
    <username>meteorWJ</username>
    <password>123</password>
  </user>
  <user>
    <username>eleven</username>
    <password>111</password>
  </user>
  <user>
    <username>crystal</username>
    <password>123</password>
  </user>
</root>