• c# winform 实际操作XML代码,包括创建、保存、查询、删除窗体演示


    1.添加一窗体,加入3个按钮控件、1个文本控件、1个datagridview控件、2个隐藏label控件。

    2.代码

    执行效果

     

    (1)按钮1创建xml文件,按文本框中整数添加到执行文件同目录下的data.xml文件;(2)按钮2在datagridview表中输出xml文件内容;(3)按钮3可以对表中选项进行删除行。

    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;
    using System.Threading;
    using System.Text.RegularExpressions;

    namespace WindowsFormsApplication9
    {
        public partial class Form1 : Form
        {
            //定义公共对象:
            public int row;
            XmlDocument xmldoc;
            XmlElement xmlelement;
            DataTable check_dt = new DataTable();
            public Form1()
            {
                InitializeComponent();
                dataGridView1.RowHeadersVisible = false;
                dataGridView1.DataSource = null;
               
            }

            private void button1_Click(object sender, EventArgs e)
            {
                if (!IsInteger(textBox1.Text))
                {
                    MessageBox.Show("请输入整数", "提示");
                    this.textBox1.Focus();
            
                    return;
                }
                row = Convert.ToInt32(textBox1.Text);
           
                xmldoc = new XmlDocument();
                //加入XML的声明段落,
                XmlDeclaration xmldeclaration;
                xmldeclaration = xmldoc.CreateXmlDeclaration("1.0", "gb2312", null);
                xmldoc.AppendChild(xmldeclaration);

                //加入一个根元素
                xmlelement = xmldoc.CreateElement("", "Books", "");
                xmldoc.AppendChild(xmlelement);
                //加入另外一个元素
                for (int i = 1; i < row+1; i++)
                {
                    Thread.Sleep(1);
                    string x = System.DateTime.Now.Millisecond.ToString();

                     Random ran=new Random();
                    int RandKey=ran.Next(10000000,99999999);
                    int price = ran.Next(100, 200);

                    XmlNode root = xmldoc.SelectSingleNode("Books");//查找
                    XmlElement dot = xmldoc.CreateElement("Node");//创建一个节点
                    //dot.SetAttribute("ISBN", RandKey.ToString());//设置该节点ISBN属性
                    dot.SetAttribute("ISBN", RandKey.ToString());//设置该节点ISBN属性
                    dot.SetAttribute("NAME", "数学-" + i.ToString());//设置该节点genre属性

                    XmlElement sub1 = xmldoc.CreateElement("title");
                    sub1.InnerText = "题王之中学数学-" + i.ToString();//设置文本节点
                    dot.AppendChild(sub1);//添加到节点中

                    XmlElement sub2 = xmldoc.CreateElement("price");
                    sub2.InnerText = price.ToString();
                    dot.AppendChild(sub2);

                    root.AppendChild(dot);//添加到节点中
      
                }

                //保存创建好的XML文档
                xmldoc.Save(Environment.CurrentDirectory + "\\" + "data.xml");
                label1.Text = "ok";

            }

       

            private void button2_Click(object sender, EventArgs e)
            {
                DataTable dt = new DataTable();
                dt.Columns.AddRange(new DataColumn[]{  
                 new DataColumn("NAME",typeof(string)),  
                 new DataColumn("PRICE",typeof(string))});
                String path = Environment.CurrentDirectory + "\\" + "data.xml";
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNodeList nodes = doc.SelectNodes("/Books/Node");

                foreach (XmlNode node in nodes)
                {
                    DataRow r = dt.NewRow();
                    r[0] = string.Format("{0}", node.ChildNodes[0].InnerText);
                    r[1] = string.Format("{0}", node.ChildNodes[1].InnerText);
                    dt.Rows.Add(r);
                }
               dataGridView1.RowHeadersVisible = false;
                dataGridView1.DataSource = dt;
            }

            private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
            {

                int a = 0;
                for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
                {
                    if (dataGridView1.Rows[i].Cells[0].EditedFormattedValue.ToString() == "True")
                    {
                          { a++; }
                    }
                }
                label2.Text = "选中"+ a.ToString() + "个";
               
             
            }

            private void button3_Click(object sender, EventArgs e)
            {

                String path = Environment.CurrentDirectory + "\\" + "data.xml";
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNodeList nodes = doc.SelectNodes("/Books/Node");

                foreach (XmlNode node in nodes)
                {


                    for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
                    {
                        if (dataGridView1.Rows[i].Cells[0].EditedFormattedValue.ToString() == "True" && dataGridView1.Rows[i].Cells[2].EditedFormattedValue.ToString() == string.Format("{0}", node.ChildNodes[1].InnerText))
                        {

                            node.ParentNode.RemoveChild(node);
                        }
                    }

                }
                doc.Save(Environment.CurrentDirectory + "\\" + "data.xml");
            }
            public static bool IsInteger(string s)
            {
                string pattern = @"^\d*$";
                return Regex.IsMatch(s, pattern);
            }

        }
    }
     

     

  • 相关阅读:
    pensieve运行的经验
    [附源码]计算机毕业设计springboot房屋租赁信息系统
    LVS + Keepalived群集
    【天梯赛 - L2习题集】啃题(6 / 44)
    Codeforces Round 897 (Div. 2)
    golang设置socket选项参数SO_LINGER、SO_SNDBUF
    在推荐系统中,BPRloss、Embloss、CrossEntropyloss是怎么计算的,代表的意义是什么
    云原生数据湖以存储、计算、数据管理等能力通过信通院评测认证
    Wireshark把DDoS照原形
    基于51的单片机GPS定位系统设计
  • 原文地址:https://blog.csdn.net/liheao/article/details/125894135