C# XML描述与实例增删改

  • 概述
  1. 用于小型项目数据存储,信息传递。系统配置文件等
  • 特点
  1. 必须有根节点(对比HTML)
  2. 标签只能自定义 (对比HTML)
  3. 头声明可有可无建议书写<?xml version="1.0" encoding="utf-8" ?>
  4. 都是成对的标签,并区分大小写(对比HTML)
  5. 特殊字符特殊写法 &lt;< &gt;> &amp;& &apos;* &quot;"
  6. 标签可设置属性
  • 应用实例 基于winform
  1. 描述 小型学生管理软件 实现增删查
  2. 下方为代码
  3. XML文件(数据库)
<?xml version="1.0" encoding="utf-8" ?>
<root>
    <class>
        <student>
            <Id>1</Id>
            <Name>张三</Name>
            <Age>3</Age>
            <Sex>男</Sex>
            <Class>3</Class>
        </student>
        <student>
            <Id>2</Id>
            <Name>李四</Name>
            <Age>4</Age>
            <Sex>女</Sex>
            <Class>3</Class>
        </student>

    </class>
</root>
  • 查询并转换成StudentModel对象
using System.Xml;
string XmlParth = "myxml.xml";
public class StudentModel
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Sex { get; set; }
        public string Age { get; set; }
        public string Class { get; set; }
    }
  public List<T> GetXmlToModel<T>(T model)
        {
            List<T> result = new List<T>();

            XmlDocument doc = new XmlDocument();
            doc.Load(XmlParth);//根据路径读取文件
            XmlNodeList students = doc.SelectNodes("root/class/student");//再次定位到具体的某个节点
            //以下就是动态的给model绑定查出来的值,并添加到集合
            var type = model.GetType();//获取model所有字段
            //循环学生的所有节点
            foreach (XmlNode node in students)
            {
                T add = System.Activator.CreateInstance<T>();//实例一个新的model对象用于添加到集合
                foreach (System.Reflection.PropertyInfo pro in type.GetProperties())
                {
                    var rre = node.SelectSingleNode(pro.Name);
                    if (rre != null)
                    {   //单条单字段赋值
                        pro.SetValue(add, rre.InnerText.ToString(), null);
                    }
                }
                result.Add(add);
            }
            return result;


        }
//调用
   gridControl1.DataSource = GetXmlToModel(new StudentModel()).OrderBy(a=>a.Id).ToList();
            gridView1.RefreshData();
  • 新增
  //AppendChild添加节点,一层层加
        public string AddXml<T>(T model)
        {
            string result = "";
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(XmlParth);
                XmlNode classNode = doc.SelectSingleNode("root/class");
                XmlElement studentnew = doc.CreateElement("student");
                var type = model.GetType();
                foreach (System.Reflection.PropertyInfo pro in type.GetProperties())
                {
                    XmlElement chele = doc.CreateElement(pro.Name); 
                    chele.InnerText = pro.GetValue(model).ToString();

                    studentnew.AppendChild(chele);//学生下面添加子节点
                } 
                classNode.AppendChild(studentnew);//班级节点下添加学生
                doc.Save(XmlParth);
                return result;
            }
            catch (Exception e)
            {
                return e.Message;
            }
         
           
        }
  • 删除
  //删除遵循从里到外RemoveAll,RemoveChild
        public string DelXml(int Id)
        {
            string str = "";
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(XmlParth);
                XmlNode classNode = doc.SelectSingleNode("root/class");
                XmlNodeList nodes = classNode.ChildNodes;
                foreach (XmlNode re in nodes)
                {
                    if (re.SelectSingleNode("Id").InnerText == Id.ToString())
                    {
                        re.RemoveAll();
                        classNode.RemoveChild(re);
                        doc.Save(XmlParth);
                        str = "";
                        break;
                    }
                }
                return str;
            }
            catch (Exception e)
            {
                return e.Message;
            }
            

        }

 

 

注意:doc.Save()后才生效

posted @ 2022-12-14 09:21  人走茶亦凉  阅读(43)  评论(0编辑  收藏  举报