C# 简单的操作xml读取与追加节点

这篇博客介绍了如何使用C#进行XML文件的读取和追加节点操作。通过`OpenFileDialog`打开XML文件,然后利用`XmlDocument`加载文件并遍历节点,将数据填充到`DataGridView`。同时,提供了保存XML文件的方法,包括新增数据到现有XML文件中。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

 public partial class Form1 : Form
    {
        string openpath = "";
        int datacount = 0;
        public Form1()
        {
            InitializeComponent();
        }

        /*
       一、打开文件对话框(OpenFileDialog)

      1、 OpenFileDialog控件有以下基本属性
        
            InitialDirectory 对话框的初始目录
            Filter 要在对话框中显示的文件筛选器,例如,"文本文件(*.txt)|*.txt|所有文件(*.*)||*.*"
            FilterIndex 在对话框中选择的文件筛选器的索引,如果选第一项就设为1
            RestoreDirectory 控制对话框在关闭之前是否恢复当前目录
            FileName 第一个在对话框中显示的文件或最后一个选取的文件
            Title 将显示在对话框标题栏中的字符
            AddExtension 是否自动添加默认扩展名
            CheckPathExists
            在对话框返回之前,检查指定路径是否存在
            DefaultExt 默认扩展名
            DereferenceLinks 在从对话框返回前是否取消引用快捷方式
            ShowHelp
            启用"帮助"按钮
            ValiDateNames 控制对话框检查文件名中是否不含有无效的字符或序列

      2、 OpenFileDialog控件有以下常用事件
        
            FileOk 当用户点击"打开"或"保存"按钮时要处理的事件
            HelpRequest 当用户点击"帮助"按钮时要处理的事件
         
         */


        #region 打开XML文件
        /// <summary>
        /// 打开XML文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenXML_Click(object sender, EventArgs e)
        {
            string dir = "D:\\测试的xml文件夹";
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
            OpenFileDialog openfile = new OpenFileDialog();
            openfile.InitialDirectory = dir;//注意这里写路径时要用c:\\而不是c:\
            openfile.Filter = "*.xml|*.*"; // "文本文件|*.*|C#文件|*.cs|所有文件|*.*";
            openfile.RestoreDirectory = true;

            DialogResult result = openfile.ShowDialog();
            if (result == DialogResult.OK)
            {
                dataGridView1.Rows.Clear();
                string path = openfile.FileName;
                openpath = path;
                OpenXMLFile(path);
            }
        }
        #endregion

        #region 保存xml文件
        /// <summary>
        /// 保存xml文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveXML_Click(object sender, EventArgs e)
        {
            SavaXML(openpath);
        }
        #endregion

        #region 读取xml文件中的信息
        /// <summary>
        /// 读取xml文件中的信息
        /// </summary>
        /// <param name="path">打开文件的路径</param>
        private void OpenXMLFile(string path)
        {
            try
            {
                XmlDocument xmldoc = new XmlDocument();
                if (File.Exists(path))
                {
                    xmldoc.Load(path);
                    XmlNode root = xmldoc.SelectSingleNode("Courses");
                    if(root.HasChildNodes)
                    {
                        foreach (XmlNode node in root.SelectNodes("Course"))
                        {
                            XmlElement elem = (XmlElement)node;
                            string name = elem.GetAttribute("name");
                            string teacher = elem.GetAttribute("teacher");
                            XmlElement classelem = (XmlElement)node.SelectSingleNode("classes");
                            string classname = classelem.InnerText;
                            XmlElement stuelem = (XmlElement)node.SelectSingleNode("student");
                            string stucount = stuelem.InnerText;

                            //DataGridViewRow row = new DataGridViewRow();
                             
                            ////row.Cells["Course"].Value = name;
                            ////row.Cells["classname"].Value = classname;
                            ////row.Cells["teacher"].Value = teacher;
                            ////row.Cells["student"].Value = stucount;

                            //row.Cells[0].Value = name;
                            //row.Cells[1].Value = classname;
                            //row.Cells[2].Value = teacher;
                            //row.Cells[3].Value = stucount;

                            dataGridView1.Rows.Add(name,classname,teacher,stucount);  
                        }

                        datacount = dataGridView1.Rows.Count;
                    }
                    
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region 保存XML文件信息
        /// <summary>
        /// 保存XML文件信息
        /// </summary>
        /// <param name="path"></param>
        private void SavaXML(string path)
        {
            try
            {
                if (File.Exists(openpath))
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(path);
                    XmlNode root = xmlDoc.SelectSingleNode("Courses");//查找<Employees>

                    for (int i = datacount-1; i < dataGridView1.Rows.Count-1; i++)
                    {
                        string Course = dataGridView1.Rows[i].Cells["Course"].Value.ToString();
                        string classname = dataGridView1.Rows[i].Cells["classname"].Value.ToString();
                        string teacher = dataGridView1.Rows[i].Cells["teacher"].Value.ToString();
                        string student = dataGridView1.Rows[i].Cells["student"].Value.ToString();

                        XmlElement courseElem = xmlDoc.CreateElement("Course");//创建一个<Node>节点
                        courseElem.SetAttribute("name", Course);//设置该节点genre属性
                        courseElem.SetAttribute("teacher", teacher);//设置该节点ISBN属性

                        XmlElement classes = xmlDoc.CreateElement("classes");
                        classes.InnerText = classname;//设置文本节点
                        courseElem.AppendChild(classes);//添加到<Node>节点中

                        XmlElement studentElem = xmlDoc.CreateElement("student");
                        studentElem.InnerText = student;//设置文本节点
                        courseElem.AppendChild(studentElem);//添加到<Node>节点中


                        root.AppendChild(courseElem);//添加到<Employees>节点中
                    }
                     
                    xmlDoc.Save(path);
                    
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
        }

        #endregion

        #region 新增信息
        /// <summary>
        /// 新增信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            string course = txtCourse.Text.Trim();
            string classname = txtClass.Text.Trim();
            string teacher = txtTeacher.Text.Trim();
            string count = txtCourse.Text.Trim();
            if (course == "")
            {
                MessageBox.Show("课程不能为空");
                return;
            }
            if (classname == "")
            {
                MessageBox.Show("班级不能为空");
                return;
            }
            if (teacher == "")
            {
                MessageBox.Show("老师不能为空");
                return;
            }
            if (count == "")
            {
                MessageBox.Show("学生数不能为空");
                return;
            }
            dataGridView1.Rows.Add(course, classname, teacher, count);
        }
        #endregion

    }

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值