在平时开发系统功能的时候,我们经常会碰到一些需求需要经常性的发生变化,比如 系统版本、更新日志 等等。这个时候用一个XML文件来替代数据库,就会变的简便很多。
前段时候我也正好需要改个需求,是关于客户公司年假的设置,大致需求是这样的:
<?xml version="1.0"?> <YearLeaveConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <!--下列标签首字母必须大写--> <LeaveItems> <LeaveItem> <YearStart>0</YearStart> <YearEnd>1</YearEnd> <LeaveDay>0</LeaveDay> </LeaveItem> <LeaveItem> <YearStart>1</YearStart> <YearEnd>2</YearEnd> <LeaveDay>2</LeaveDay> </LeaveItem> <LeaveItem> <YearStart>2</YearStart> <YearEnd>5</YearEnd> <LeaveDay>3</LeaveDay> </LeaveItem> <LeaveItem> <YearStart>5</YearStart> <YearEnd>8</YearEnd> <LeaveDay>6</LeaveDay> </LeaveItem> <LeaveItem> <YearStart>8</YearStart> <YearEnd>100</YearEnd> <LeaveDay>10</LeaveDay> </LeaveItem> </LeaveItems> </YearLeaveConfig>
2、实体类
public class LeaveItem { public int YearStart { get; set; } public int YearEnd { get; set; } public int LeaveDay { get; set; } } public class YearLeaveConfig { public LeaveItem[] LeaveItems { get; set; } }
3、读取XML
static void Main(string[] args) { string strPth = Environment.CurrentDirectory; YearLeaveConfig yearLeave = (YearLeaveConfig)new XmlSerializer(typeof(YearLeaveConfig)).Deserialize(new FileStream(strPth + @"\YearLeaveConfig.xml", FileMode.Open)); foreach (LeaveItem item in yearLeave.LeaveItems) { Console.WriteLine(string.Format("年假设置:{0}~~{1}年的享受年假:{2}天",item.YearStart,item.YearEnd,item.LeaveDay)); } Console.Read(); }
关于如何读取XML文件的一个简单方法,布布扣,bubuko.com
原文:http://www.cnblogs.com/zhangliangzlee/p/XML.html