在C#程序中,創建、寫入、讀取XML文件的方法


 一、在C#程序中,創建、寫入、讀取XML文件的方法

        1、創建和讀取XML文件的方法,Values為需要寫入的值     

 

 1  private void WriteXML(string Values)
 2         {        
 3                //保存的XML的地址
 4                 string XMLPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\" + "文件的名稱.xml";             
 5                 XmlDocument xmlDoc = new XmlDocument(); //引入using System.Xml  命名空間
 6              
 7                 //創建類型聲明
 8                 xmlDoc = new XmlDocument();
 9                 XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
10                 xmlDoc.AppendChild(node);
11                 //創建父節點
12                 XmlNode root = xmlDoc.CreateElement("父節點");
13                 xmlDoc.AppendChild(root);
14                 //創建子節點,寫入值
15                 node = xmlDoc.CreateNode(XmlNodeType.Element, "子節點", null);
16                 node.InnerText = Values;
17                 root.AppendChild(node);
18                 xmlDoc.Save(XMLPath);         
19         }
20 
21  

 

2、讀取XML文件中存入的值方法    

   

 1 private void ReadXML()
 2         {          
 3                 XmlDocument xmlDoc = new XmlDocument();
 4                 string XMLPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\" + "文件的名稱.xml";
 5                 //如果文件存在      
 6                 if (File.Exists(XMLPath))
 7                 {
 8                     xmlDoc.Load(XMLPath); //從指定的URL加載XML文檔
 9                     XmlNode Values= xmlDoc.SelectSingleNode("父節點").SelectSingleNode("子節點");
10                     string str= Values.InnerText; //獲取到存入的值為 string        
11                 }
12            }

 


免責聲明!

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



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