首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

关于读写XML文件解决方案

2012-01-31 
关于读写XML文件如我有一XML文件如下,我要如何读写其中userID和userName两个的值.?xmlversion 1.0 enc

关于读写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();

热点排行