在软件开发过程中,经常使用到XML文件作为配置文件,保存一些配置信息。 为了方便对程序配置文件的读写,微软特别为.Net程序提供了程序配置文件,如web.config,App.config,这些配置文件通常会自动生成在程序启动目录下,并具有特定的格式。同时,.Net Framework还提供了一组读写配置文件的接口,这些接口被包含在命名空间System.Configuration中。 但由于接口固定,系统自带的配置文件格式不容易扩展,这些配置文件通常只能用来保存一些简单的信息,比如数据库连接信息或应用程序标识。【示例代码下载】


其它的数据类定义如下:
- /// <summary>
- /// XML保存和设置接口
- /// </summary>
- public interface IXmlStorage
- {
- /// <summary>
- /// 根据对应的XML节点来获取各属性值
- /// </summary>
- /// <param name="factoTypeNode">读取信息的节点</param>
- void GetValueFromXml(System.Xml.XmlNode objectNode);
- /// <summary>
- /// 将对象本身格式化为XML
- /// </summary>
- /// <param name="xmldoc">需要写入的文档</param>
- /// <param name="parentEle">生成节点的父元素节点</param>
- void SetValueToXml(System.Xml.XmlDocument xmldoc, XmlElement parentEle);
- }
其中,作为所有数据对象中的最大(级别)的对象,DataBase除了实现XML节点读写接口外,还需要提供加载和写入XML文件的方法,供外部代码调用,这也是读写XML文件的唯一入
- /// <summary>
- /// 数据库对象
- /// </summary>
- public class DataBase : IXmlStorage
- {
- /// <summary>
- /// 数据库名称
- /// </summary>
- public string Name = string.Empty;
- /// <summary>
- /// 描述
- /// </summary>
- public string Description = string.Empty;
- /// <summary>
- /// 创建日期
- /// </summary>
- public DateTime CreateDate = DateTime.Now;
- /// <summary>
- /// 数据表集合
- /// </summary>
- public List<Table> TableList = new List<Table>();
- /// <summary>
- /// 配置文件实例
- /// </summary>
- XmlDocument xmldoc = new XmlDocument();
- /// <summary>
- /// 默认配置文件名称
- /// </summary>
- public static readonly string DefaultConfigXml = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar + "DatabaseConfig.xml";
- #region IXmlStorage Members
- public void GetValueFromXml(XmlNode objectNode)
- {
- if (objectNode == null)
- return;
- if (objectNode.Name.Equals("database", StringComparison.CurrentCultureIgnoreCase))
- {
- XmlAttributeCollection attCol = objectNode.Attributes;
- //从节点属性中获取值
- for (int i = 0; i < attCol.Count; i++)
- {
- XmlAttribute att = attCol[i];
- if (att.Name.Equals("name", StringComparison.CurrentCultureIgnoreCase))
- this.Name = att.Value;
- if (att.Name.Equals("description", StringComparison.CurrentCultureIgnoreCase))
- this.Description = att.Value;
- if (att.Name.Equals("date", StringComparison.CurrentCultureIgnoreCase))
- {
- try
- {
- this.CreateDate = DateTime.Parse(att.Value);
- }
- catch
- {
- this.CreateDate = DateTime.Now;
- }
- }
- }
- //先清空原来的下级节点内容(因为有可能多次重复加载)
- this.TableList.Clear();
- //获取下一级子节点的值
- XmlNodeList nodeList = objectNode.ChildNodes;
- if (nodeList != null && nodeList.Count > 0)
- {
- for (int j = 0; j < nodeList.Count; j++)
- {
- XmlNode node = nodeList[j];
- if (node.Name.Equals("table", StringComparison.CurrentCultureIgnoreCase))
- {
- Table t = new Table();
- t.GetValueFromXml(node);
- this.TableList.Add(t);
- }
- }
- }
- }
- }
- public void SetValueToXml(XmlDocument xmldoc, XmlElement parentEle)
- {
- XmlElement dbEle = xmldoc.CreateElement("Database");
- dbEle.SetAttribute("name", this.Name);
- dbEle.SetAttribute("description", this.Description);
- dbEle.SetAttribute("date", this.CreateDate.ToString());
- xmldoc.AppendChild(dbEle); //由于此时是根节点,故parentEle为空
- //添加下一级的子节点
- for (int i = 0; i < this.TableList.Count; i++)
- {
- Table t = this.TableList[i];
- t.SetValueToXml(xmldoc, dbEle);
- }
- }
- #endregion
- }
- /// <summary>
- /// 数据表
- /// </summary>
- public class Table : IXmlStorage
- {
- /// <summary>
- /// 表名
- /// </summary>
- public string Name = string.Empty;
- /// <summary>
- /// 描述
- /// </summary>
- public string Description = string.Empty;
- /// <summary>
- /// 列集合
- /// </summary>
- public List<Column> ColumnList = new List<Column>();
- #region IXmlStorage Members
- public void GetValueFromXml(System.Xml.XmlNode objectNode)
- {
- if (objectNode == null)
- return;
- if (objectNode.Name.Equals("table", StringComparison.CurrentCultureIgnoreCase))
- {
- XmlAttributeCollection attCol = objectNode.Attributes;
- //从节点属性中获取值
- for (int i = 0; i < attCol.Count; i++)
- {
- XmlAttribute att = attCol[i];
- if (att.Name.Equals("name", StringComparison.CurrentCultureIgnoreCase))
- this.Name = att.Value;
- if (att.Name.Equals("description", StringComparison.CurrentCultureIgnoreCase))
- this.Description = att.Value;
- }
- //先清空原来的下级节点内容(因为有可能多次重复加载)
- this.ColumnList.Clear();
- //获取下一级子节点的值
- XmlNodeList nodeList = objectNode.ChildNodes;
- if (nodeList != null && nodeList.Count > 0)
- {
- for (int j = 0; j < nodeList.Count; j++)
- {
- XmlNode node = nodeList[j];
- if (node.Name.Equals("column", StringComparison.CurrentCultureIgnoreCase))
- {
- Column c = new Column();
- c.GetValueFromXml(node);
- this.ColumnList.Add(c);
- }
- }
- }
- }
- }
- public void SetValueToXml(System.Xml.XmlDocument xmldoc, System.Xml.XmlElement parentEle)
- {
- XmlElement tblEle = xmldoc.CreateElement("Table");
- tblEle.SetAttribute("name", this.Name);
- tblEle.SetAttribute("description", this.Description);
- parentEle.AppendChild(tblEle); //由于此时是根节点,故parentEle为空
- //添加下一级的子节点
- for (int i = 0; i < this.ColumnList.Count; i++)
- {
- Column c = this.ColumnList[i];
- c.SetValueToXml(xmldoc, tblEle);
- }
- }
- #endregion
- }
完成了所有数据对象的定义,我们就可以通过XML文件来配置和存储这些数据。
- #region 读取和保存XML文件
- public bool LoadFromFile(string xmlPath)
- {
- try
- {
- this.xmldoc.Load(xmlPath);
- XmlNode rootNode = this.xmldoc.SelectSingleNode("//Database");
- if (rootNode != null)
- {
- this.GetValueFromXml(rootNode);
- }
- }
- catch (Exception ex)
- {
- string msg = "加载配置文件失败,发生异常:" + ex.Message;
- throw new Exception(msg);
- }
- return true;
- }
- public bool SaveToFile(string xmlPath)
- {
- try
- {
- this.xmldoc = new XmlDocument(); //重新构造一个XML文档
- XmlDeclaration xDeclare = this.xmldoc.CreateXmlDeclaration("1.0", "GB2312", null);
- this.xmldoc.AppendChild(xDeclare);
- this.SetValueToXml(this.xmldoc, null);
- this.xmldoc.Save(xmlPath);
- return true;
- }
- catch (XmlException ex)
- {
- throw new Exception("保存配置文件失败,发生异常:" + ex.Message);
- }
- }
- #endregion
总结:
- DataBase db = new DataBase();
- db.Name = "数据库1";
- db.Description = "for test";
- Table tbl = new Table();
- tbl.Name = "Student";
- tbl.Description = "学生信息表";
- db.TableList.Add(tbl);
- Column c1 = new Column();
- c1.Name = "StudentName";
- c1.ColumnType = 1;
- c1.IsNullable = false;
- c1.Remark = "姓名";
- Column c2 = new Column();
- c2.Name = "Number";
- c2.ColumnType = 1;
- c2.IsPrimaryKey = true;
- c2.Remark = "学号";
- Column c3 = new Column();
- c3.Name = "Age";
- c3.ColumnType = 2;
- c3.Remark = "年龄";
- tbl.ColumnList.Add(c1);
- tbl.ColumnList.Add(c2);
- tbl.ColumnList.Add(c3);
- //保存数据到XML文件
- db.SaveToFile("D:\\mytest.xml");
- //从XML文件中加载数据
- DataBase db2 = new DataBase();
- db2.LoadFromFile("D:\\mytest.xml");