关于读写XML文件
如我有一XML文件如下,我要如何读写其中userID和userName两个的值.
<?xml version= "1.0 " encoding= "utf-8 "?>
<configuration>
<appSettings>
<add key= "userID " value= "001 " />
<add key= "userName " value= "admini " />
</appSettings>
</configuration>
------解决方案--------------------是web.config或app.config吗?
是的话读出来只要System.Configuration.ConfigurationSettings.AppSettings[ "userID "]就行了
------解决方案--------------------写入貌似没有现成的方法,不过当它xml处理就行了。
XmlDocument doc = new XmlDocument();
doc.Load( "c:\\test.xml ");
XmlNode node = doc.SelectSingleNode( "/configuration/appSettings/add[@key= 'userID '] ");
if (node != null)
{
// 把userID 改成 002
node.Attributes[ "value "].Value = "002 ";
}
doc.Save( "c:\\test.xml ");
------解决方案--------------------try..
//读取
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Console.WriteLine(config.AppSettings.Settings[ "userID "].Value + " : " + config.AppSettings.Settings[ "userName "].Value);
//更改
config.AppSettings.Settings[ "userID "].Value = "123 ";
config.AppSettings.Settings[ "userName "].Value = "test ";
config.Save();
------解决方案--------------------这个对了
//读取
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Console.WriteLine(config.AppSettings.Settings[ "userID "].Value + " : " + config.AppSettings.Settings[ "userName "].Value);
//更改
config.AppSettings.Settings[ "userID "].Value = "123 ";
config.AppSettings.Settings[ "userName "].Value = "test ";
config.Save();