加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Net XML操作

发布时间:2020-12-16 23:45:01 所属栏目:百科 来源:网络整理
导读:一般xml文件用来保存初次配置内容,在项目搭建的时候 会创建一个xml 文件到启动文件中。 ps:这里注意了创建txt文件 要注意utf-8 编码? 保存一下,修改后缀为.xml。 第一步读取xml文件: string xmlPath = Application.StartupPath + "/config.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);
标签:? xml节点操作,? xml属性操作

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读