• .Net XML操作


    一般xml文件用来保存初次配置内容,在项目搭建的时候 会创建一个xml 文件到启动文件中。

    ps:这里注意了创建txt文件 要注意utf-8 编码  保存一下,修改后缀为.xml。

    第一步读取xml文件:

                string xmlPath = Application.StartupPath + "/config.xml";//获取 程序启动文件路径
    
                XmlDocument xml = new XmlDocument();
                xml.Load(xmlPath);//读取文件
    
                XmlElement root = xml.DocumentElement;//获取根节点
    
                //添加 节点
                XmlElement node = xml.CreateElement("Student");
                //节点属性 赋值
                node.SetAttribute("Name", "小明");
                node.SetAttribute("Age", "22");
                node.SetAttribute("Sex", "");
                root.AppendChild(node);
    
                xml.Save(xmlPath);//保存 xml文件

    string xmlPath = Application.StartupPath + "/config.xml"; 这句代码后面加的  是自己 xml文件的名字。嘿!

    最后别忘了 保存一下xml文件,要不操作就白作了。

    然后看看对xml文件的操作:

    string xmlPath = Application.StartupPath + "/config.xml";//获取 程序启动文件路径
     //获取 节点内容
                XmlDocument xml = new XmlDocument();
                xml.Load(xmlPath);//读取文件地址
    
                XmlElement root = xml.DocumentElement;//获取跟节点
                XmlNode student = root.SelectSingleNode("Student");//读取节点
                string cc =  student.Attributes["Name"].Value;//读取节点 指定子节点
    
                //修改节点内容
                student.Attributes["Name"].Value = "小红";
                Console.WriteLine(student.Attributes["Name"].Value);
    
                //删除属性
                XmlAttribute Sex = student.Attributes["Sex"];
                student.Attributes.Remove(Sex);
    
                //移除指定节点
                //root.RemoveChild(student);
    
    
                xml.Save(xmlPath);//保存xml文件

    删除属性值 就是会把属性删掉,

    删除节点属性值:

    student.Attributes["Sex"].RemoveAll();

    这样会直接把该属性 的值 设置为"",控制字符串。

    追加节点属性:

                //追加属性
                XmlNode Score = xml.CreateNode(XmlNodeType.Attribute,"Score",null);
                Score.Value = "44";
                student.Attributes.SetNamedItem(Score);

    在相对节点追加属性嘿!

     有觉得不清晰的老铁,说出模糊点留言,我做修改,来完善阅读体验!!!!

  • 相关阅读:
    OData – 权限管理
    Identity – Authorize Custom Authorization Policy Providers
    CSS – W3Schools 学习笔记 (1)
    OData – How It Work
    OData – Custom Serialize & Deserialize
    ASP.NET Core – System.Text.Json
    Identity – Authorize
    ASP.NET Core – Custom Input formatters For Partial Update and Handle Underposting
    as3 Matrix用法
    as3页游聊天框点击透明区域及普通文本支持寻路方案
  • 原文地址:https://www.cnblogs.com/nnqwbc/p/8206105.html
Copyright © 2020-2023  润新知