关于配置文件
2004-05-20 19:33 Yuanyi Wang 阅读(1006) 评论(2) 编辑 收藏 举报 最近在看.Text的源代码,发现其配置文件的读取很有意思。
原来用XmlRootAttribute、XmlAttributeAttribute还有XmlElementAtrribute类就可以很方便的读取和保存配置文件。我写了一个简单的例子。
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using NUnit.Framework;
namespace AAA
{
///
/// EEE 的摘要说明。
///
[XmlRoot( "frameworkConfig" )]
public class FrameworkConfig
{
public FrameworkConfig (){}
private string applicationName = string.Empty;
[XmlAttribute( "applicationName" )]
public string ApplicationName
{
set
{
applicationName = value;
}
get
{
return applicationName;
}
}
private string cacheName;
[XmlElement( "cacheName" )]
public string CacheName
{
set
{
cacheName = value;
}
get
{
return cacheName;
}
}
}
///
/// TestFrameworkConfig 的摘要说明。
///
[TestFixture]
public class TestFrameworkConfig
{
public TestFrameworkConfig()
{
}
public void TestCreateFrameworkConfig()
{
StringBuilder sb = new StringBuilder();
sb = sb.Append( "
.Append( "
.Append( "
StringReader stream = new StringReader( sb.ToString() );
XmlSerializer xs = new XmlSerializer( typeof( FrameworkConfig ) );
FrameworkConfig fc = (FrameworkConfig)xs.Deserialize( stream );
System.Console.WriteLine( fc.ApplicationName );
System.Console.WriteLine( fc.CacheName );
//Assert.IsTrue( fc.ApplicationName == string.Empty );
Assert.IsTrue( fc.ApplicationName == "PPPPP" );
Assert.IsTrue( fc.CacheName == "ppppp" );
}
}
}
保存配置的时候直接串行化就好了!!
真不知道.Net还有多少这样方便的用法。