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

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

        一、建立和讀取XML文件的方法,Values爲須要寫入的值     node

 

 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

 

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

   

 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            }
相關文章
相關標籤/搜索