using System;
using System.Collections;
using System.Xml;
using System.IO;
using System.Text;

namespace UUN
{
    /// <summary>
    /// 对XML格式设置文件的处理
    /// </summary>
    public class 设置
    {
        public Hashtable 数据项;
        public object this[object 项名称]
        {
            get
            {
                return 数据项[项名称];
            }
            set
            {
                数据项[项名称] = value;
            }
        }

        public 设置(String XML内容)
        {
            if (XML内容 == "")
            {
                this.数据项 = new Hashtable();
                return;
            }
            this.数据项 = 读取设置(XML内容);
        }
        /// <summary>
        /// 将一段XML数据转换为集合
        /// </summary>
        /// <param name="XML内容">XML数据的内容</param>
        /// <returns>数据集合</returns>
        public Hashtable 读取设置(String XML内容)
        {
            Hashtable 返回值 = new Hashtable();
            XmlReader 读取 = XmlReader.Create(new StringReader(XML内容));

            while (读取.Read())
                if (读取.NodeType == XmlNodeType.Element)
                    if (读取.Name == "set")
                        返回值.Add(读取.GetAttribute("name"), 读取.GetAttribute("value"));
            读取.Close();

            return 返回值;
        }
        /// <summary>
        /// 将设置集合生成相应的XML
        /// </summary>
        /// <returns>XML内容</returns>
        public String 生成XML()
        {
            StringBuilder 返回值 = new StringBuilder();
            XmlWriterSettings XWS = new XmlWriterSettings();
            XWS.Indent = true;
            XWS.ConformanceLevel = ConformanceLevel.Auto;
            XWS.IndentChars = "\t";
            XmlWriter 写入 = XmlWriter.Create(返回值,XWS);
            写入.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");
            写入.WriteStartElement("data");

            foreach (object 键 in 数据项.Keys)
            {
                写入.WriteStartElement("set");
                写入.WriteAttributeString("name", Convert.ToString(键));
                写入.WriteAttributeString("value", Convert.ToString(数据项[键]));
                写入.WriteEndElement();
            }

            写入.WriteEndElement();
            写入.Close();

            return 返回值.ToString();
        }
    }
}