zoukankan      html  css  js  c++  java
  • C# 操作Xml

    在我们项目的开发中,会常常对Xml文件进行操作,以下是我总结的几个基本操作的方法:

     

    1、装载Xml文件

            XmlDocument xmldoc;
    
            //装载Xml文件
            public void LoadXml()
            {
                /*
                 * 1、判断该路径是否存在着Person.xml文件,如不存在则创建
                 * 2、加载Person.xml
                 */
    
                if (!File.Exists(path))
                {
                    CreateFile();
                    return;
                }
    
                xmldoc = new XmlDocument();
                xmldoc.Load(path);
            }

    2、创建XMl文档

            //创建xml文件
            public void CreateFile()
            {
                xmldoc = new XmlDocument();
    
                //1、创建段落声明<?xml version="1.0" encoding="GB2312" standalone="yes"?>
                XmlDeclaration xDec = xmldoc.CreateXmlDeclaration("1.0", "GB2312", "yes");
                xmldoc.AppendChild(xDec);
                //2、创建根节点Persons
                XmlNode rootNode = xmldoc.CreateElement("Persons");
                xmldoc.AppendChild(rootNode);
    
                xmldoc.Save(path);
            }

    3、读取Xml文档中的数据(PerModel是一个实体类)

     

            public void ReadXml()
            {
                LoadXml();
    
                List<PerModel> listper = new List<PerModel>();
    
                //获取根节点Persons
                XmlNode rootNode = xmldoc.SelectSingleNode("Persons");
                //获取所有的Person元素
                XmlNodeList xnl = rootNode.ChildNodes;
                if (xnl != null && xnl.Count > 0)
                {
                    foreach (XmlNode xn in xnl)
                    {
                        XmlElement xe = (XmlElement)xn;
                        PerModel per = new PerModel();//PerModel是一个实体类
                        per.Name = xe.GetAttribute("Mz");//获取属性值
                        per.Sfzjh = xe.GetAttribute("Zjh");//获取属性值
    
                        XmlNodeList xnl2 = xe.ChildNodes;
                        per.Age = xnl2.Item(0).InnerText.ToString().Trim();
                        per.Sex = xnl2.Item(1).InnerText.ToString().Trim();
                        per.Adress = xnl2.Item(2).InnerText.ToString().Trim();
    
                        listper.Add(per);
                    }
                }
                dgv.DataSource = null;
                dgv.DataSource = listper;
            }

     

    4、Xml文档插入数据

        //新增节点
            public void AddNode(string Mz, string Zjh, string Nl, string Xb, string Dz)
            {
                LoadXml();
                //获取根节点
                XmlNode rootNode = xmldoc.SelectSingleNode("Persons");
                //创建子节点Person
                XmlElement pele = xmldoc.CreateElement("Person");
                //Person的两个属性Mz ,Zjh
                pele.SetAttribute("Mz", Mz);
                pele.SetAttribute("Zjh", Zjh);
    
                //创建新元素 Nl 
                XmlElement nlEle = xmldoc.CreateElement("Nl");
                nlEle.InnerText = Nl;
                pele.AppendChild(nlEle);
    
                //创建新元素 Xb
                XmlElement xbEle = xmldoc.CreateElement("Xb");
                xbEle.InnerText = Xb;
                pele.AppendChild(xbEle);
    
                //创建新元素 Dz
                XmlElement dzEle = xmldoc.CreateElement("Dz");
                dzEle.InnerText = Dz;
                pele.AppendChild(dzEle);
    
                //添加Person节点
                rootNode.AppendChild(pele);
                xmldoc.Save(path);
            }

    5、修改xml文档数据

       public void UpdateXml()
            {
                LoadXml();
    
                XmlNode rootNode = xmldoc.SelectSingleNode("//Persons");
                XmlElement xe = (XmlElement)rootNode.SelectSingleNode("//Persons/Person[@Zjh='" + dgv.CurrentRow.Cells[1].Value.ToString().Trim() + "']");
                xe.SetAttribute("Mz", dgv.CurrentRow.Cells[0].Value.ToString().Trim());//除了修改属性值,也可以通过SetAttribute来增加一个属性
                xe.GetElementsByTagName("Nl").Item(0).InnerText = dgv.CurrentRow.Cells[2].Value.ToString().Trim();
                xe.GetElementsByTagName("Xb").Item(0).InnerText = dgv.CurrentRow.Cells[3].Value.ToString().Trim();
                xe.GetElementsByTagName("Dz").Item(0).InnerText = dgv.CurrentRow.Cells[4].Value.ToString().Trim();
          
                xmldoc.Save(path);
            }

    6、删除xml文档数据

     public void DeleteXml()
            {
                LoadXml();
    
                XmlNode rootNode = xmldoc.SelectSingleNode("//Persons");
    
                //删除年龄大于5岁小于10岁的人
                XmlNodeList xnl = rootNode.SelectNodes("//Persons/Person[Nl<'10' and Nl>'5']");
                for (int i = 0; i < xnl.Count; i++)
                {
                    xnl[i].ParentNode.RemoveChild(xnl[i]);
                }
    
                //删除属性‘Zjh’值为2017052202的节点
                XmlNode xn  = rootNode.SelectSingleNode("//Persons/Person[@Zjh='2017052202']");
                xn.ParentNode.RemoveChild(xn);
    
                xmldoc.Save(path);
            }

    附完整源码,及运行效果图:

    using System.Xml;
    using System.IO;
    
    namespace Test_XML
    {
        public partial class Form2 : Form
        {
            /*
             * Button
             * ············
             * btn_Read     读取
             * btn_Add      新增
             * btn_update   更新
             * btn_Del      删除
             * ············
             * 
             * TextBox
             * ············
             * txt_mz      名字
             * txt_zjh     证件号
             * txt_nl      年龄
             * txt_xb      性别
             * txt_dz      地址
             * ············
             * 
             * DataGridView
             * ············
             * dgv
            */
    
            string path = @"D:Person.xml";
    
            public Form2()
            {
                InitializeComponent();
            }
    
            private void Form2_Load(object sender, EventArgs e)
            {
                dgv.AutoGenerateColumns = false;
                dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            }
    
            //新增按钮
            private void btn_Add_Click(object sender, EventArgs e)
            {
                AddNode(txt_mz.Text.Trim(), txt_zjh.Text.Trim(), txt_nl.Text.Trim(), txt_xb.Text.Trim(), txt_dz.Text.Trim());
                //更新数据
                ReadXml();
            }
    
            //读取按钮
            private void btn_Read_Click(object sender, EventArgs e)
            {
                ReadXml();
            }
    
            //更新按钮
            private void btn_update_Click(object sender, EventArgs e)
            {
                UpdateXml();
                //更新数据
                ReadXml();
            }
    
            //删除按钮
            private void btn_Del_Click(object sender, EventArgs e)
            {
                DeleteXml();
                //更新数据
                ReadXml();
            }
    
            XmlDocument xmldoc;
    
            //装载Xml文件
            public void LoadXml()
            {
                /*
                 * 1、判断该路径是否存在着Person.xml文件,如不存在则创建
                 * 2、加载Person.xml
                 */
    
                if (!File.Exists(path))
                {
                    CreateFile();
                    return;
                }
    
                xmldoc = new XmlDocument();
                xmldoc.Load(path);
            }
    
            //创建xml文件
            public void CreateFile()
            {
                xmldoc = new XmlDocument();
    
                //1、创建段落声明<?xml version="1.0" encoding="GB2312" standalone="yes"?>
                XmlDeclaration xDec = xmldoc.CreateXmlDeclaration("1.0", "GB2312", "yes");
                xmldoc.AppendChild(xDec);
                //2、创建根节点Persons
                XmlNode rootNode = xmldoc.CreateElement("Persons");
                xmldoc.AppendChild(rootNode);
    
                xmldoc.Save(path);
            }
    
            //新增节点
            public void AddNode(string Mz, string Zjh, string Nl, string Xb, string Dz)
            {
                LoadXml();
                //获取根节点
                XmlNode rootNode = xmldoc.SelectSingleNode("Persons");
                //创建子节点Person
                XmlElement pele = xmldoc.CreateElement("Person");
                //Person的两个属性Mz ,Zjh
                pele.SetAttribute("Mz", Mz);
                pele.SetAttribute("Zjh", Zjh);
    
                //创建新元素 Nl 
                XmlElement nlEle = xmldoc.CreateElement("Nl");
                nlEle.InnerText = Nl;
                pele.AppendChild(nlEle);
    
                //创建新元素 Xb
                XmlElement xbEle = xmldoc.CreateElement("Xb");
                xbEle.InnerText = Xb;
                pele.AppendChild(xbEle);
    
                //创建新元素 Dz
                XmlElement dzEle = xmldoc.CreateElement("Dz");
                dzEle.InnerText = Dz;
                pele.AppendChild(dzEle);
    
                //添加Person节点
                rootNode.AppendChild(pele);
                xmldoc.Save(path);
            }
    
            public void ReadXml()
            {
                LoadXml();
    
                List<PerModel> listper = new List<PerModel>();
    
                //获取根节点Persons
                XmlNode rootNode = xmldoc.SelectSingleNode("Persons");
                //获取所有的Person元素
                XmlNodeList xnl = rootNode.ChildNodes;
                if (xnl != null && xnl.Count > 0)
                {
                    foreach (XmlNode xn in xnl)
                    {
                        XmlElement xe = (XmlElement)xn;
                        PerModel per = new PerModel();//PerModel是一个实体类
                        per.Name = xe.GetAttribute("Mz");//获取属性值
                        per.Sfzjh = xe.GetAttribute("Zjh");//获取属性值
    
                        XmlNodeList xnl2 = xe.ChildNodes;
                        per.Age = xnl2.Item(0).InnerText.ToString().Trim();
                        per.Sex = xnl2.Item(1).InnerText.ToString().Trim();
                        per.Adress = xnl2.Item(2).InnerText.ToString().Trim();
    
                        listper.Add(per);
                    }
                }
                dgv.DataSource = null;
                dgv.DataSource = listper;
            }
    
            public void UpdateXml()
            {
                LoadXml();
    
                XmlNode rootNode = xmldoc.SelectSingleNode("//Persons");
                XmlElement xe = (XmlElement)rootNode.SelectSingleNode("//Persons/Person[@Zjh='" + dgv.CurrentRow.Cells[1].Value.ToString().Trim() + "']");
                xe.SetAttribute("Mz", dgv.CurrentRow.Cells[0].Value.ToString().Trim());//除了修改属性值,也可以通过SetAttribute来增加一个属性
                xe.GetElementsByTagName("Nl").Item(0).InnerText = dgv.CurrentRow.Cells[2].Value.ToString().Trim();
                xe.GetElementsByTagName("Xb").Item(0).InnerText = dgv.CurrentRow.Cells[3].Value.ToString().Trim();
                xe.GetElementsByTagName("Dz").Item(0).InnerText = dgv.CurrentRow.Cells[4].Value.ToString().Trim();
          
                xmldoc.Save(path);
            }
    
            public void DeleteXml()
            {
                LoadXml();
    
                XmlNode rootNode = xmldoc.SelectSingleNode("//Persons");
    
                //删除年龄大于5岁小于10岁的人
                XmlNodeList xnl = rootNode.SelectNodes("//Persons/Person[Nl<'10' and Nl>'5']");
                for (int i = 0; i < xnl.Count; i++)
                {
                    xnl[i].ParentNode.RemoveChild(xnl[i]);
                }
    
                //删除属性‘Zjh’值为2017052202的节点
                XmlNode xn  = rootNode.SelectSingleNode("//Persons/Person[@Zjh='2017052202']");
                xn.ParentNode.RemoveChild(xn);
    
                xmldoc.Save(path);
            }
        }
    }
    Form2源码
    namespace Test_XML
    {
        /// <summary>
        /// Person实体类
        /// </summary>
        [Serializable]
        public class PerModel
        {
            /// <summary>
            /// 姓名
            /// </summary>
            public string Name { get; set; }
    
            /// <summary>
            /// 证件号
            /// </summary>
            public string Sfzjh { get;set;}
    
            /// <summary>
            /// 年龄
            /// </summary>
            public string Age { get; set; }
    
            /// <summary>
            /// 性别
            /// </summary>
            public string Sex { get; set; }
    
            /// <summary>
            /// 家庭地址
            /// </summary>
            public string Adress { get; set; }
        }
    }
    PerModel实体类

    运行效果图:

     

  • 相关阅读:
    在Salesforce中创建Approval Process
    用C#基于WCF创建TCP的Service供Client端调用
    用 C# 实现一个简单的 Rest Service 供外部调用
    在Salesforce中将 Decimal 数据转换成美元格式
    在Asp.Net MVC中PartialView与EditorFor和DisplayFor的区别
    在Salesforce中对某一个Object添加自定义的Button和Link
    【LeetCode】227. Basic Calculator II
    【LeetCode】226. Invert Binary Tree
    【LeetCode】225. Implement Stack using Queues
    【LeetCode】224. Basic Calculator
  • 原文地址:https://www.cnblogs.com/haibing0107/p/6899897.html
Copyright © 2011-2022 走看看