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 }