C#使用LINQ操作XML配置文件读取写入数据 配置文件config.xml如下: <?xml version="1.0" encoding="utf-8"?> <Soft> <SN RegCode="01234567890"></SN> <LoginConfig SqlServer="." SqlDB="db" UserCode="sa" UserPwd="123"> </LoginConfig> </Soft> 读取指定元素指定属性的值: /// <summary> /// 返回XMl文件指定元素的指定属性值 /// </summary> /// <param name="xmlElement">指定元素</param> /// <param name="xmlAttribute">指定属性</param> /// <returns></returns> public static string getXmlValue(string xmlElement,string xmlAttribute) { XDocument xmlDoc = XDocument.Load(xmlName); var results = from c in xmlDoc.Descendants(xmlElement) select c; string s = ""; foreach (var result in results) { s = result.Attribute(xmlAttribute).Value.ToString(); } return s; } 设置指定元素指定属性的值: /// <summary> /// 设置XMl文件指定元素的指定属性的值 /// </summary> /// <param name="xmlElement">指定元素</param> /// <param name="xmlAttribute">指定属性</param> /// <param name="xmlValue">指定值</param> public static void setXmlValue(string xmlElement, string xmlAttribute, string xmlValue) { XDocument xmlDoc = XDocument.Load(xmlName); xmlDoc.Element("Soft").Element(xmlElement).Attribute(xmlAttribute).SetValue(xmlValue); xmlDoc.Save(xmlName); } } }