.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);

在相對節點追加屬性嘿!

 有覺得不清晰的老鐵,說出模糊點留言,我做修改,來完善閱讀體驗!!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM