C#之XML增删改查

2017-07-22  本文已影响39人  幻凌风

界面预览

界面预览.jpg

准备XML数据

<?xml version="1.0" encoding="utf-8"?>
<Users>
  <user id="994">
    <name>123</name>
    <age>123</age>
    <gender>女</gender>
    <password>123</password>
  </user>
  <user id="360">
    <name>甄志丙</name>
    <password>haha</password>
    <gender>女</gender>
    <age>43</age>
  </user>
  <user id="123">
    <name>汉子</name>
    <password>123abc</password>
    <age>18</age>
    <gender>男</gender>
  </user>
  <user id="222">
    <name>222</name>
    <age>222</age>
    <gender>男</gender>
    <password>2222</password>
  </user>
  <user id="2468">
    <name>昆昆</name>
    <age>26</age>
    <gender>女</gender>
    <password>33567</password>
  </user>
  <user id="888">
    <name>小云</name>
    <age>28</age>
    <gender>男</gender>
    <password>YUNWEN0305</password>
  </user>
  <user id="12">
    <name>sudo</name>
    <age>23</age>
    <gender>男</gender>
    <password>adsda</password>
  </user>
  <user id="13">
    <name>sudos</name>
    <age>23</age>
    <gender>男</gender>
    <password>adsdasas</password>
  </user>
  <user id="434">
    <name>fdgsdfd</name>
    <age>23</age>
    <gender>男</gender>
    <password>adsdasassd</password>
  </user>
</Users>

定义XML数据对象对象的User类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataGridViewExample
{
    class User
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public Char Gender { get; set; }
        public int Age { get; set; }
        public string Password { get; set; }
    }
}

实现代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace DataGridViewExample
{
    public partial class UserForm : Form
    {
        public UserForm()
        {
            InitializeComponent();
        }

        private void UserForm_Load(object sender, EventArgs e)
        {
            LoadData();
        }
        void LoadData()
        {
            UserDataGridView.RowHeadersVisible = false;//取消显示第一列
            //将选项模式改为选中一整行
            UserDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            //取消默认选中第一行
            //UserDataGridView.SelectedRows[0].Visible = false;
            //存储对象的集合
            List<User> listUser = new List<User>();
            //开始读取数据,赋值给集合中的对象
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load("UserData.xml");
            //获取根节点
            XmlElement Users = xdoc.DocumentElement;
            //获得根节点下所有子节点
            XmlNodeList xnl = Users.ChildNodes;
            foreach (XmlNode item in xnl)
            {
                //将从XML文档中读取到的数据赋值给集合中的对象的属性
                listUser.Add(new User()
                {
                    ID = Convert.ToInt32(item.Attributes["id"].Value),
                    Name = item["name"].InnerText,
                    Age = Convert.ToInt32(item["age"].InnerText),
                    Gender = Convert.ToChar(item["gender"].InnerText),
                    Password = item["password"].InnerText
                });
            }
            //将数据赋值给DataGridView
            UserDataGridView.DataSource = listUser;
        }

        //注册
        private void RegestButton_Click(object sender, EventArgs e)
        {
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load("UserData.xml");

            //获得根节点
            XmlElement users = xdoc.DocumentElement;
            //新添加的子节点
            XmlElement user = xdoc.CreateElement("user");
            user.SetAttribute("id", AddIDTextBox.Text.Trim());

            XmlElement name = xdoc.CreateElement("name");
            name.InnerText = AddNameTextBox.Text.Trim();
            user.AppendChild(name);

            XmlElement age = xdoc.CreateElement("age");
            age.InnerText = AddAgeTextBox.Text.Trim();
            user.AppendChild(age);

            XmlElement gender = xdoc.CreateElement("gender");
            gender.InnerText = AddRbManButton.Checked ? "男" : "女";
            user.AppendChild(gender);

            XmlElement password = xdoc.CreateElement("password");
            password.InnerText = AddPasswordTextBox.Text;
            user.AppendChild(password);

            users.AppendChild(user);

            //保存数据到XML文档
            xdoc.Save("UserData.xml");
            //从XML加载数据到DataGridView
            LoadData();
            MessageBox.Show("注册成功!");
        }
        //删除
        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //删除指定的行数据
            //获得当前选中行的ID
            string id = UserDataGridView.SelectedRows[0].Cells[0].Value.ToString();
            //根据ID进行删除
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load("UserData.xml");
            XmlElement users = xdoc.DocumentElement;
            //获得要删除的节点
            XmlNode xn = users.SelectSingleNode("/Users/user[@id=" + id +"]");
            //通过父节点移除子节点,包括子节点下面的节点
            users.RemoveChild(xn);
            //xn.RemoveAll();//删除子节点,但是自己还在
            xdoc.Save("UserData.xml");
            LoadData();
            MessageBox.Show("删除成功!");
        }
        //赋值
        private void UserDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //将选中行的数据赋值给文本框
            UpdateIDTextBox.Text = UserDataGridView.SelectedRows[0].Cells[0].Value.ToString();
            UpdateNameTextBox.Text = UserDataGridView.SelectedRows[0].Cells[1].Value.ToString();
            UpdateAgeTextBox.Text = UserDataGridView.SelectedRows[0].Cells[3].Value.ToString();
            UpdatePasswordTextBox.Text = UserDataGridView.SelectedRows[0].Cells[4].Value.ToString();
            string gender = UserDataGridView.SelectedRows[0].Cells[2].Value.ToString();
            if (gender=="男")
            {
                UpdateRbManButton.Checked = true;
            }
            else
            {
                UpdateRbWomanButton.Checked = true;
            }
        }
        //修改
        private void UpdateButton_Click(object sender, EventArgs e)
        {
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load("UserData.xml");
            XmlElement users = xdoc.DocumentElement;
            //根据ID修改其它值
            string id = UpdateIDTextBox.Text;
            XmlNode xn = users.SelectSingleNode("/Users/user[@id=" + id + "]");
            xn["name"].InnerText = UpdateNameTextBox.Text;
            xn["age"].InnerText = UpdateAgeTextBox.Text;
            xn["password"].InnerText = UpdatePasswordTextBox.Text;
            string gender = UpdateRbManButton.Checked ? "男" : "女";
            xn["gender"].InnerText = gender;
            MessageBox.Show("修改成功!");
            xdoc.Save("UserData.xml");
            LoadData();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读