用xml做配置文件详解

用xml做配置文件详解  


  用xml文件做配置文件,我因为刚刚做完一个播放器,有点心得。每种xml文件都必须写个类,就像三层架构中一样,每个表必须要有三个类一样,一个model,一个dal,一个bll。我深深地觉得配置文件也应当用一个类或多个类进行封装。业务层只调用这个封装的类,而不用越过它直接用System.Xml中的类去存取。且看我写的实例。
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
using System.IO;

namespace PlayerApp
{

    ///
    /// 播放列表类
    ///

    public class PlayList
    {

        private List _mediaList = new List();
        private string _filePath = "";



        #region 属性

        ///
        /// 播放列表中的媒体
        ///

        public List MediaList
        {
            get { return _mediaList; }
        }


        ///
        /// 播放列表的加载的路径
        ///

        public string PlayListPath
        {
            get { return _filePath; }
            set { _filePath = value; }
        }


        #endregion



        public PlayList(string path)
        {
            this.Load(path);
        }


        ///
        /// 将播放列表加载至此实例
        ///

        ///
        public void Load(string path)
        {

            XmlDocument xmlDoc = new XmlAccess(path).Document;

            XmlNodeList list = xmlDoc.SelectNodes(@"/PlayList/*");
            foreach (XmlNode node in list)
            {
                Media m = new Media();
                m.Name = node.SelectSingleNode("name").InnerText;
                m.Path = node.SelectSingleNode("path").InnerText;
                m.Type = node.SelectSingleNode("type").InnerText;

                _mediaList.Add(m);

            }

            xmlDoc = null;
        }



        ///
        /// 将此实例中的数据保存至播放列表文件中
        ///

        ///
        public void Save(string path)
        {
            XmlAccess xml = new XmlAccess(path);

            //先删除原有内容
            xml.Delete(@"/PlayList/*", false);

            //将列表中的数据保存至xml
            foreach (Media m in _mediaList)
            {
                string content = "{0}{1}{2}";
                content = string.Format(content, XmlAccess.Quote(m.Type), XmlAccess.Quote(m.Name), XmlAccess.Quote(m.Path));
                xml.InsertElement("/PlayList", "media", content);
            }
            xml.Save();
            xml.Dispose();
        }



        ///
        /// 加入音频文件
        ///

        ///
        public void AddMedia(Media m)
        {
            _mediaList.Add(m);
        }



        ///
        /// 从列表中删除制定文件
        ///

        ///
        public void Delete(Media m)
        {
            _mediaList.Remove(m);
        }



        ///
        /// 清空播放列表
        ///

        public void Clear()
        {
            _mediaList.Clear();
        }


        ///
        /// 在列表中查找文件
        ///

        /// 正则表达式
        ///
        public List Find(string reg)
        {
            List result = new List();
            foreach (Media m in _mediaList)
                if(Regex.IsMatch(Path.GetFileNameWithoutExtension(m.Path),reg)) result.Add(m);

            return result;
        }


    }



    ///
    /// 表示播放列表中的媒体信息
    ///

    public class Media
    {
        private string _name = "";
        private string _path = "";
        private string _type = "";

        ///
        /// 媒体的标题名(用于显示在播放列表里面)
        ///

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        ///
        /// 媒体所代表文件的路径
        ///

        public string Path
        {
            get { return _path; }
            set { _path = value; }
        }


        ///
        /// 媒体是音频(0)还是视频(1)
        ///

        public string Type
        {
            get { return _type; }
            set { _type = value; }
        }



        ///
        /// 此媒体是否为音频
        ///

        ///
        public bool IsAudio()
        {
            return _type.Trim() == "0" ? true : false;
        }
    }

}


  这儿有两个类,一个是PlayList类,播放列表类,一个是Media。媒体类,代表一个媒体文件。我播放列表文件的结构如下:


 
    0
    江南
    E:\dotnet\TestWinApp\TestWinApp\music\江南.mp3
 

 
    1
    新不了情-015
    F:\电视剧\新不了情\新不了情-015.rmvb
 

 
    1
    新不了情-016
    F:\电视剧\新不了情\新不了情-016.rmvb
 


  这个播放列表定义得很简单。由上可总结,像这种节点,最好定义一个相关联的类,这样,就更显得结构合理,清晰。另外,这样的类有一个特点,它有三个必备的东西:
  一、加载函数
  二、保存函数
  三、与配置文件中相关内容相应的成员(加载与保存都以此为纽带)
  关于存取xml,我根据前面讲过的代码,修改了一下,得XmlAccess,如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;


namespace PlayerApp
{

    ///
    /// 这个类有借鉴价值,有空来加强加强
    ///

    public class XmlAccess
    {
        ///
        /// 要处理的xml的路径
        ///

        protected string strXmlFile;
        protected XmlDocument objXmlDoc = new XmlDocument();


        ///
        /// 获得对应的xmlDocument对象,有时不得己要用到
        /// ,在某些情况下,这个类并不能满足需求时,就得
        /// 老老实实地用System.Xml下的API了。
        ///

        public XmlDocument Document
        {
            get { return objXmlDoc; }
        }



        public XmlAccess(string xmlFile)
        {
            try { objXmlDoc.Load(xmlFile); }
            catch (System.Exception ex)
            {
                throw ex;
            }
            strXmlFile = xmlFile;
        }




        ///
        /// 将指定xpath的节点用指定内容替换。当然是替换InnerText。
        ///

        ///
        ///
        public void Replace(string xmlPathNode, string content)
        {
            objXmlDoc.SelectSingleNode(xmlPathNode).InnerText = content;
        }



        ///
        /// 删除指定节点
        ///

        /// xpath
        /// 是否只删除单个节点
        public void Delete(string node,bool bSingle)
        {
            if (bSingle)
            {
                XmlNode n = objXmlDoc.SelectSingleNode(node);
                n.ParentNode.RemoveChild(n);
            }
            else
            {
                XmlNodeList list = objXmlDoc.SelectNodes(node);
                foreach (XmlNode n in list)
                {
                    n.ParentNode.RemoveChild(n);
                }
            }
        }


        ///
        /// 插入节点,在mainNode下创建childNode,然后为childNode创建子节点element,
        /// element的InnerText为content
        ///

        ///
        ///
        ///
        ///
        public void InsertNode(string mainNode, string childNode, string element, string content)
        {
            XmlNode objRootNode = objXmlDoc.SelectSingleNode(mainNode);
            XmlElement objChildNode = objXmlDoc.CreateElement(childNode);
            objRootNode.AppendChild(objChildNode);
            XmlElement objElement = objXmlDoc.CreateElement(element);
            objElement.InnerText = content;
            objChildNode.AppendChild(objElement);
        }


        ///
        /// 在mainNode下创建子元素节点element,并设置它的attrib属性为attribContent,
        /// 将其innerXml设为xmlContent,功能强大。且返回此插入的元素节点的引用。
        ///

        /// 父结点
        /// 要插入元素的标签名
        /// 要设置的属性
        /// 要设置的属性值
        /// 要设置的xml内容
        /// 插入元素的引用
        public XmlElement InsertElement(string mainNode, string element, string attrib, string attribContent, string xmlContent)
        {
            XmlNode objNode = objXmlDoc.SelectSingleNode(mainNode);
            XmlElement objElement = objXmlDoc.CreateElement(element);
            objElement.SetAttribute(attrib, attribContent);
            objElement.InnerXml = xmlContent;
            objNode.AppendChild(objElement);

        }


        ///
        /// 在mainNode创建指定元素element,并且设其xml内容为xmlContent,
        /// 且返回插入的元素节点引用
        ///

        /// 父节点
        /// 要插入元素的标签名
        /// 要插入元素的xml内容
        /// 插入元素的引用
        public XmlElement InsertElement(string mainNode, string element, string xmlContent)
        {
            XmlNode objNode = objXmlDoc.SelectSingleNode(mainNode);
            XmlElement objElement = objXmlDoc.CreateElement(element);
            objElement.InnerXml = xmlContent;
            objNode.AppendChild(objElement);
            return objElement;
        }



        ///
        /// 读取指定节点的某属性值
        ///

        ///
        ///
        ///
        public string GetAttribute(string xpath, string attr)
        {
            XmlNode node = objXmlDoc.SelectSingleNode(xpath);
            return node.Attributes[attr].Value;
        }



        ///
        /// 写指定节点的某属性
        ///

        ///
        ///
        ///
        public void SetAttribute(string xpath, string attr, string value)
        {
            XmlNode node = objXmlDoc.SelectSingleNode(xpath);
            node.Attributes[attr].Value = value;
            Save();
        }



        ///
        /// 查到的所有节点的InnerText的数组
        ///

        ///
        ///
        public string[] GetNodeList(string xmlPathNode)
        {
            XmlNodeList xnList = objXmlDoc.SelectNodes(xmlPathNode);
            string[] strArr = new string[xnList.Count];
            for (int i = 0; i < xnList.Count; i++)
            {
                strArr[i] = xnList[i].InnerText;
            }
            return strArr;
        }



        ///
        /// 满足xpath且某属性的值为指定的值的节点的InnerText
        ///

        ///
        ///
        ///
        ///
        public string GetNodeText(string xmlPathNode, string attrib, string attribContent)
        {
            string xnStr = "";
            XmlNodeList xnList = objXmlDoc.SelectNodes(xmlPathNode);
            foreach (XmlNode xn in xnList)
            {
                if (xn.Attributes[attrib] != null)
                {
                    if (xn.Attributes[attrib].Value == attribContent)
                    {
                        xnStr = xn.InnerText;
                        break;
                    }
                }
            }
            return xnStr;
        }



        ///
        /// 获得满足指定XPath的第一个元素的innerText
        ///

        ///
        ///
        public string GetNodeText(string xmlPathNode)
        {
            return objXmlDoc.SelectSingleNode(xmlPathNode).InnerText;
        }



        ///
        /// 设置满足指定XPath的第一个元素的innerText
        ///

        ///
        ///
        public void SetNodeText(string xpath, string text)
        {
            objXmlDoc.SelectSingleNode(xpath).InnerText = text;
        }


        ///
        /// 保存修改
        ///

        public void Save()
        {
            try
            {
                objXmlDoc.Save(strXmlFile);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            //objXmlDoc = null;
        }



        ///
        /// 释放资源
        ///

        public void Dispose()
        {
            objXmlDoc = null;
        }


        ///
        /// 为字符串的某些特殊字符转义
        ///

        ///
        ///
        public static string Quote(string input)
        {
            input = input.Replace("&", "&");
            input = input.Replace("<", "<");
            input = input.Replace(">", ">");
            input = input.Replace("\"", """);
            input = input.Replace("\'", "'");


            return input;
        }

    }
}

你可能感兴趣的:(用xml做配置文件详解)