C# winform窗体简单保存界面控件参数到xml

原文:C# winform窗体简单保存界面控件参数到xml

引用网上的 XMLHelper 地址 :https://www.cnblogs.com/chnboy/archive/2009/04/02/1427652.html

稍做修改

C# winform窗体简单保存界面控件参数到xml
using System;
using System.Linq;
using System.Xml;

namespace FormTest
{
    /// <summary>
    /// XMLHelper XML文档操作管理器
    /// </summary>
    public class XMLHelper
    {
        public XMLHelper()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }


        #region XML文档节点查询和读取
        /// <summary>
        /// 选择匹配XPath表达式的第一个节点XmlNode.
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名")</param>
        /// <returns>返回XmlNode</returns>
        public static XmlNode GetXmlNodeByXpath(string xmlFileName, string xpath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlFileName); //加载XML文档
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                return xmlNode;
            }
            catch (Exception ex)
            {
                return null;
                //throw ex; //这里可以定义你自己的异常处理
            }
        }

        /// <summary>
        /// 选择匹配XPath表达式的节点列表XmlNodeList.
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名")</param>
        /// <returns>返回XmlNodeList</returns>
        public static XmlNodeList GetXmlNodeListByXpath(string xmlFileName, string xpath)
        {
            XmlDocument xmlDoc = new XmlDocument();

            try
            {
                xmlDoc.Load(xmlFileName); //加载XML文档
                XmlNodeList xmlNodeList = xmlDoc.SelectNodes(xpath);
                return xmlNodeList;
            }
            catch (Exception ex)
            {
                return null;
                //throw ex; //这里可以定义你自己的异常处理
            }
        }

        /// <summary>
        /// 选择匹配XPath表达式的第一个节点的匹配xmlAttributeName的属性XmlAttribute.
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param>
        /// <returns>返回xmlAttributeName</returns>
        public static XmlAttribute GetXmlAttribute(string xmlFileName, string xpath, string xmlAttributeName)
        {
            string content = string.Empty;
            XmlDocument xmlDoc = new XmlDocument();
            XmlAttribute xmlAttribute = null;
            try
            {
                xmlDoc.Load(xmlFileName); //加载XML文档
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    if (xmlNode.Attributes.Count > 0)
                    {
                        xmlAttribute = xmlNode.Attributes[xmlAttributeName];
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex; //这里可以定义你自己的异常处理
            }
            return xmlAttribute;
        }
        /// <summary>
        /// 选择匹配XPath表达式的第一个节点的匹配xmlAttributeName的属性XmlAttribute.
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <param name="name">要匹配xmlAttributeName的属性的子节点名称</param>
        /// <param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param>
        /// <param name="xmlAttributeValues">要匹配xmlAttributeName的属性值</param>
        /// <returns>返回xmlAttributeName的属性的子节点名称InnerText</returns>
        public static string GetXmlByAttribute(string xmlFileName, string xpath, string name, string xmlAttributeName, string xmlAttributeValues)
        {
            string content = string.Empty;
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlFileName); //加载XML文档
                //主要
                XmlNodeList xlist = xmlDoc.SelectNodes(xpath);
                XmlNode xmlNode = xlist.Cast<XmlNode>().Where(o => o.Attributes.Cast<XmlAttribute>().FirstOrDefault(a => a.Name == xmlAttributeName && a.Value == xmlAttributeValues) != null).FirstOrDefault();

                //XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    foreach (XmlNode node in xmlNode.ChildNodes)
                    {
                        if (node.Name.ToLower() == name.ToLower())
                        {
                            //存在此节点则返回InnerText
                            content = node.InnerText;
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex; //这里可以定义你自己的异常处理
            }
            return content;
        }
        /// <summary>
        /// 选择匹配XPath表达式的第一个节点的匹配xmlAttributeName的属性XmlAttribute.
        /// </summary>
        /// <param name="xmlFileName"></param>
        /// <param name="xpath"></param>
        /// <param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param>
        /// <param name="xmlAttributeValues">要匹配xmlAttributeName的属性值</param>
        /// <returns>返回节点InnerText</returns>
        public static string GetXmlByAttribute(string xmlFileName, string xpath, string xmlAttributeName, string xmlAttributeValues)
        {
            string content = string.Empty;
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlFileName); //加载XML文档
                //主要
                XmlNodeList xlist = xmlDoc.SelectNodes(xpath);
                XmlNode xmlNode = xlist.Cast<XmlNode>().Where(o => o.Attributes.Cast<XmlAttribute>().FirstOrDefault(a => a.Name == xmlAttributeName && a.Value == xmlAttributeValues) != null).FirstOrDefault();

                //XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    content = xmlNode.InnerText;
                }
            }
            catch (Exception ex)
            {
                throw ex; //这里可以定义你自己的异常处理
            }
            return content;
        }
        #endregion

        #region XML文档创建和节点或属性的添加、修改
        /// <summary>
        /// 创建一个XML文档
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="rootNodeName">XML文档根节点名称(须指定一个根节点名称)</param>
        /// <param name="version">XML文档版本号(必须为:"1.0")</param>
        /// <param name="encoding">XML文档编码方式</param>
        /// <param name="standalone">该值必须是"yes"或"no",如果为null,Save方法不在XML声明上写出独立属性</param>
        /// <returns>成功返回true,失败返回false</returns>
        public static bool CreateXmlDocument(string xmlFileName, string rootNodeName, string version, string encoding, string standalone)
        {
            bool isSuccess = false;
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration(version, encoding, standalone);
                XmlNode root = xmlDoc.CreateElement(rootNodeName);
                xmlDoc.AppendChild(xmlDeclaration);
                xmlDoc.AppendChild(root);
                xmlDoc.Save(xmlFileName);
                isSuccess = true;
            }
            catch (Exception ex)
            {
                throw ex; //这里可以定义你自己的异常处理
            }
            return isSuccess;
        }

        /// <summary>
        /// 依据匹配XPath表达式的第一个节点来创建它的子节点(如果此节点已存在则追加一个新的同名节点
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <param name="xmlNodeName">要匹配xmlNodeName的节点名称</param>
        /// <param name="innerText">节点文本值</param>
        /// <param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param>
        /// <param name="value">属性值</param>
        /// <returns>成功返回true,失败返回false</returns>
        public static bool CreateXmlNodeByXPath(string xmlFileName, string xpath, string xmlNodeName, string innerText, string xmlAttributeName, string value)
        {
            bool isSuccess = false;
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlFileName); //加载XML文档
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    //存不存在此节点都创建
                    XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);
                    subElement.InnerXml = innerText;

                    //如果属性和值参数都不为空则在此新节点上新增属性
                    if (!string.IsNullOrEmpty(xmlAttributeName) && !string.IsNullOrEmpty(value))
                    {
                        XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(xmlAttributeName);
                        xmlAttribute.Value = value;
                        subElement.Attributes.Append(xmlAttribute);
                    }

                    xmlNode.AppendChild(subElement);
                }
                xmlDoc.Save(xmlFileName); //保存到XML文档
                isSuccess = true;
            }
            catch (Exception ex)
            {
                throw ex; //这里可以定义你自己的异常处理
            }
            return isSuccess;
        }

        /// <summary>
        /// 依据匹配XPath表达式的第一个节点来创建或更新它的子节点(如果节点存在则更新,不存在则创建)
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <param name="xmlNodeName">要匹配xmlNodeName的节点名称</param>
        /// <param name="innerText">节点文本值</param>
        /// <returns>成功返回true,失败返回false</returns>
        public static bool CreateOrUpdateXmlNodeByXPath(string xmlFileName, string xpath, string xmlNodeName, string innerText)
        {
            bool isSuccess = false;
            bool isExistsNode = false;//标识节点是否存在
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlFileName); //加载XML文档
                //XmlNodeList xlist = xmlDoc.SelectNodes(xpath);
                //XmlNode xmlNode = xlist.Cast<XmlNode>().Where(o => o.InnerText == innerText).FirstOrDefault();
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    //遍历xpath节点下的所有子节点
                    foreach (XmlNode node in xmlNode.ChildNodes)
                    {
                        //XmlAttribute att = node.Attributes.Cast<XmlAttribute>().Where(o => o.Name == innerText).FirstOrDefault();
                        if (node.Name.ToLower() == xmlNodeName.ToLower())
                        {
                            //存在此节点则更新
                            node.InnerXml = innerText;
                            isExistsNode = true;
                            break;
                        }
                    }
                    if (!isExistsNode)
                    {
                        //不存在此节点则创建
                        XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);
                        subElement.InnerXml = innerText;
                        xmlNode.AppendChild(subElement);
                    }
                }
                xmlDoc.Save(xmlFileName); //保存到XML文档
                isSuccess = true;
            }
            catch (Exception ex)
            {
                throw ex; //这里可以定义你自己的异常处理
            }
            return isSuccess;
        }

        /// <summary>
        /// 依据匹配XPath表达式的第一个节点来创建或更新它的子节点(如果节点存在则更新,不存在则创建)
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <param name="xmlNodeName">要匹配xmlNodeName的节点名称</param>
        /// <param name="innerText">节点文本值</param>
        /// <returns>成功返回true,失败返回false</returns>
        public static bool CreateOrUpdateXmlNodeByXPath(string xmlFileName, string xpath, string xmlNodeName, string innerText, string XmlAttributeName, string XmlAttributeValues)
        {
            bool isSuccess = false;
            bool isExistsNode = false;//标识节点是否存在
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlFileName); //加载XML文档
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    //遍历xpath节点下的所有子节点
                    foreach (XmlNode node in xmlNode.ChildNodes)
                    {
                        XmlAttribute att = node.Attributes.Cast<XmlAttribute>().Where(o => o.Name == XmlAttributeName && o.Value == XmlAttributeValues).FirstOrDefault();
                        if (att != null && node.Name.ToLower() == xmlNodeName.ToLower())
                        {
                            //存在此节点则更新
                            node.InnerXml = innerText;
                            isExistsNode = true;
                            #region      //遍历xpath节点中的所有属性
                            bool isExistsAttribute = false;
                            foreach (XmlAttribute attribute in node.Attributes)
                            {
                                if (attribute.Name.ToLower() == XmlAttributeName.ToLower())
                                {
                                    //节点中存在此属性则更新
                                    attribute.Value = XmlAttributeValues;
                                    isExistsAttribute = true;
                                    break;
                                }
                            }
                            if (!isExistsAttribute)
                            {
                                //节点中不存在此属性则创建
                                XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(XmlAttributeName);
                                xmlAttribute.Value = XmlAttributeValues;
                                node.Attributes.Append(xmlAttribute);
                            }
                            #endregion
                            break;
                        }
                    }
                    if (!isExistsNode)
                    {
                        //不存在此节点则创建
                        XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);
                        subElement.InnerXml = innerText;

                        XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(XmlAttributeName);
                        xmlAttribute.Value = XmlAttributeValues;
                        subElement.Attributes.Append(xmlAttribute);
                        xmlNode.AppendChild(subElement);
                    }
                }
                xmlDoc.Save(xmlFileName); //保存到XML文档
                isSuccess = true;
            }
            catch (Exception ex)
            {
                throw ex; //这里可以定义你自己的异常处理
            }
            return isSuccess;
        }

        /// <summary>
        /// 依据匹配XPath表达式的第一个节点来创建或更新它的子节点(如果节点存在则更新,不存在则创建)
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <param name="xmlNodeName">要匹配xmlNodeName的节点名称</param>
        /// <param name="innerText">节点文本值</param>
        /// <param name="parentinnerText">指定父节点文本值</param>
        /// <returns>成功返回true,失败返回false</returns>
        public static bool CreateOrUpdateXmlNodeByXPath(string xmlFileName, string xpath, string xmlNodeName, string innerText, string parentAttributevalues)
        {
            bool isSuccess = false;
            bool isExistsNode = false;//标识节点是否存在
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlFileName); //加载XML文档
                XmlNodeList xlist = xmlDoc.SelectNodes(xpath);
                //主要
                XmlNode xmlNode = xlist.Cast<XmlNode>().Where(o => o.Attributes.Cast<XmlAttribute>().FirstOrDefault(a => a.Name == "Name" && a.Value == parentAttributevalues) != null).FirstOrDefault();
                //XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    //遍历xpath节点下的所有子节点
                    foreach (XmlNode node in xmlNode.ChildNodes)
                    {
                        if (node.Name.ToLower() == xmlNodeName.ToLower())
                        {
                            //存在此节点则更新
                            node.InnerXml = innerText;
                            isExistsNode = true;
                            break;
                        }
                    }
                    if (!isExistsNode)
                    {
                        //不存在此节点则创建
                        XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);
                        subElement.InnerXml = innerText;
                        xmlNode.AppendChild(subElement);
                    }
                }
                xmlDoc.Save(xmlFileName); //保存到XML文档
                isSuccess = true;
            }
            catch (Exception ex)
            {
                throw ex; //这里可以定义你自己的异常处理
            }
            return isSuccess;
        }

        /// <summary>
        /// 依据匹配XPath表达式的第一个节点来创建或更新它的属性(如果属性存在则更新,不存在则创建)
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param>
        /// <param name="value">属性值</param>
        /// <returns>成功返回true,失败返回false</returns>
        public static bool CreateOrUpdateXmlAttributeByXPath(string xmlFileName, string xpath, string xmlAttributeName, string value)
        {
            bool isSuccess = false;
            bool isExistsAttribute = false;//标识属性是否存在
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlFileName); //加载XML文档
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    //遍历xpath节点中的所有属性
                    foreach (XmlAttribute attribute in xmlNode.Attributes)
                    {
                        if (attribute.Name.ToLower() == xmlAttributeName.ToLower())
                        {
                            //节点中存在此属性则更新
                            attribute.Value = value;
                            isExistsAttribute = true;
                            break;
                        }
                    }
                    if (!isExistsAttribute)
                    {
                        //节点中不存在此属性则创建
                        XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(xmlAttributeName);
                        xmlAttribute.Value = value;
                        xmlNode.Attributes.Append(xmlAttribute);
                    }
                }
                xmlDoc.Save(xmlFileName); //保存到XML文档
                isSuccess = true;
            }
            catch (Exception ex)
            {
                throw ex; //这里可以定义你自己的异常处理
            }
            return isSuccess;
        }
        #endregion

        #region XML文档节点或属性的删除
        /// <summary>
        /// 删除匹配XPath表达式的第一个节点(节点中的子元素同时会被删除)
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <returns>成功返回true,失败返回false</returns>
        public static bool DeleteXmlNodeByXPath(string xmlFileName, string xpath)
        {
            bool isSuccess = false;
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlFileName); //加载XML文档
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    //删除节点
                    xmlNode.ParentNode.RemoveChild(xmlNode);
                }
                xmlDoc.Save(xmlFileName); //保存到XML文档
                isSuccess = true;
            }
            catch (Exception ex)
            {
                throw ex; //这里可以定义你自己的异常处理
            }
            return isSuccess;
        }

        /// <summary>
        /// 删除匹配XPath表达式的第一个节点中的匹配参数xmlAttributeName的属性
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <param name="xmlAttributeName">要删除的xmlAttributeName的属性名称</param>
        /// <returns>成功返回true,失败返回false</returns>
        public static bool DeleteXmlAttributeByXPath(string xmlFileName, string xpath, string xmlAttributeName)
        {
            bool isSuccess = false;
            bool isExistsAttribute = false;
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlFileName); //加载XML文档
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                XmlAttribute xmlAttribute = null;
                if (xmlNode != null)
                {
                    //遍历xpath节点中的所有属性
                    foreach (XmlAttribute attribute in xmlNode.Attributes)
                    {
                        if (attribute.Name.ToLower() == xmlAttributeName.ToLower())
                        {
                            //节点中存在此属性
                            xmlAttribute = attribute;
                            isExistsAttribute = true;
                            break;
                        }
                    }
                    if (isExistsAttribute)
                    {
                        //删除节点中的属性
                        xmlNode.Attributes.Remove(xmlAttribute);
                    }
                }
                xmlDoc.Save(xmlFileName); //保存到XML文档
                isSuccess = true;
            }
            catch (Exception ex)
            {
                throw ex; //这里可以定义你自己的异常处理
            }
            return isSuccess;
        }

        /// <summary>
        /// 删除匹配XPath表达式的第一个节点中的所有属性
        /// </summary>
        /// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
        /// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
        /// <returns>成功返回true,失败返回false</returns>
        public static bool DeleteAllXmlAttributeByXPath(string xmlFileName, string xpath)
        {
            bool isSuccess = false;
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(xmlFileName); //加载XML文档
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
                if (xmlNode != null)
                {
                    //遍历xpath节点中的所有属性
                    xmlNode.Attributes.RemoveAll();
                }
                xmlDoc.Save(xmlFileName); //保存到XML文档
                isSuccess = true;
            }
            catch (Exception ex)
            {
                throw ex; //这里可以定义你自己的异常处理
            }
            return isSuccess;
        }
        #endregion

    }
}
View Code

添加 FormHelper 

C# winform窗体简单保存界面控件参数到xml
using System;
using System.Windows.Forms;

namespace FormTest
{
    public class FormHelper
    {
        //这是XML文档物理文件名(包含物理路径)
        private static string xmlFileName = Application.StartupPath + @"\Config\parameter.xml";
        //这是XML文档根节点名
        private static string rootNodeName = "Forms";

        /// <summary>
        /// 保存控件参数
        /// 放到FormClosing事件里
        /// </summary>
        /// <param name="c"></param>
        public static void SetFormParam(Control c)
        {
            CreatXml();
            string str = "";
            GetParam(c, ref str);
            str = str.TrimEnd(|);
            //保存xml文档
            string xpath = "/" + rootNodeName;  //这是新节点的父节点路径/Forms
            string nodename = "FormName"; //这是新节点名称,在父节点下新增
            string nodetext = c.Text;//窗体名
            bool isSuccess = XMLHelper.CreateOrUpdateXmlNodeByXPath(xmlFileName, xpath, nodename, "", "Name", nodetext);

            string xpath2 = xpath + "/" + nodename;  //这是新子节点的父节点路径/Forms/FormName
            string nodename2 = "parm"; //这是新子节点名称,在父节点下新增
            string nodetext2 = str;//窗体控件参数字符串
            isSuccess = XMLHelper.CreateOrUpdateXmlNodeByXPath(xmlFileName, xpath2, nodename2, nodetext2, nodetext);
        }

        /// <summary>
        /// 加载控件参数
        /// 放到Load事件尾
        /// </summary>
        /// <param name="c"></param>
        public static void LoadFormParam(Control c)
        {
            //获取xml参数文档
            if (System.IO.File.Exists(xmlFileName))
            {
                string xpath = "/" + rootNodeName + "/FormName";
                string parm = XMLHelper.GetXmlByAttribute(xmlFileName, xpath, "parm", "Name", c.Text);
                SetParam(c, parm);
            }
        }
        private static void CreatXml()
        {
            if (!System.IO.File.Exists(xmlFileName))
            {
                if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(xmlFileName)))
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(xmlFileName));
                XMLHelper.CreateXmlDocument(xmlFileName, rootNodeName, "1.0", "utf-8", null);
                //MessageBox.Show("XML文档创建成功:" + xmlFileName);
            }
        }

        private static void GetParam(Control c, ref string str)
        {
            try
            {
                foreach (Control ctl in c.Controls)
                {
                    if (ctl is TextBox)
                    {
                        TextBox tx = ctl as TextBox;
                        str += tx.Name + "$" + tx.Text + "|";
                    }
                    if (ctl is CheckBox)
                    {
                        CheckBox tx = ctl as CheckBox;
                        str += tx.Name + "$" + tx.Checked + "|";
                    }
                    if (ctl is ComboBox)
                    {
                        ComboBox tx = ctl as ComboBox;
                        str += tx.Name + "$" + tx.SelectedIndex.ToString() + "|";
                    }
                    if (ctl.Controls.Count > 0) GetParam(ctl, ref str);
                }
            }
            catch (Exception)
            {
            }
        }
        private static void SetParam(Control c, string parm)
        {
            try
            {
                foreach (Control ctl in c.Controls)
                {
                    foreach (string str in parm.Split(|))
                    {
                        if (ctl.Name == str.Split($)[0])
                        {
                            if (ctl is TextBox)
                            {
                                TextBox tx = ctl as TextBox;
                                tx.Text = str.Split($)[1];
                            }
                            if (ctl is CheckBox)
                            {
                                CheckBox tx = ctl as CheckBox;
                                tx.Checked = Convert.ToBoolean(str.Split($)[1]);
                            }
                            if (ctl is ComboBox)
                            {
                                ComboBox tx = ctl as ComboBox;
                                tx.SelectedIndex = Convert.ToInt32(str.Split($)[1]);
                            }
                        }
                    }
                    if (ctl.Controls.Count > 0) SetParam(ctl, parm);
                }
            }
            catch (Exception)
            {
            }
        }

        #region 参数保存
        private static string xmlparamFileName = Application.StartupPath + @"\Config\param.xml";
        /// <summary>
        /// 保存参数
        /// </summary>
        /// <param name="paramname">参数名</param>
        /// <param name="paramvalues">参数值</param>
        public static void SetValue(string paramname, object paramvalues)
        {
            setvalues(paramname, paramvalues.ToString());
        }
        /// <summary>
        /// 获取参数
        /// </summary>
        /// <param name="paramname">参数名</param>
        /// <param name="def">默认值</param>
        /// <returns></returns>
        public static string GetValue(string paramname, string def = "")
        {
            string str = getvalues(paramname);
            if (str == "") str = def;
            return str;
        }
        /// <summary>
        /// 获取参数
        /// </summary>
        /// <param name="paramname">参数名</param>
        /// <param name="def">默认值</param>
        /// <returns></returns>
        public static bool GetBoolValue(string paramname, bool def = false)
        {
            bool b = false;
            try
            {
                string str = getvalues(paramname);
                if (str == "") return def;
                b = Convert.ToBoolean(str.Trim());
            }
            catch (Exception)
            {
                b = def;
            }
            return b;
        }
        /// <summary>
        /// 获取参数
        /// </summary>
        /// <param name="paramname">参数名</param>
        /// <param name="def">默认值</param>
        /// <returns></returns>
        public static int GetIntValue(string paramname, int def = -1)
        {
            try
            {
                double val = GetDoubleValue(paramname, def);
                return Convert.ToInt32(val);
            }
            catch (Exception)
            {
                return def;
            }
        }
        /// <summary>
        /// 获取参数
        /// </summary>
        /// <param name="paramname">参数名</param>
        /// <param name="def">默认值</param>
        /// <returns></returns>
        public static double GetDoubleValue(string paramname, double def = -1)
        {
            try
            {
                string str = getvalues(paramname);
                if (str == "") return def;
                return Convert.ToDouble(str.Trim());
            }
            catch (Exception)
            {
                return def;
            }
        }
        private static void setvalues(string paramname, string paramvalues)
        {
            string root = "params";
            if (!System.IO.File.Exists(xmlparamFileName))
            {
                if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(xmlparamFileName)))
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(xmlparamFileName));
                XMLHelper.CreateXmlDocument(xmlparamFileName, root, "1.0", "utf-8", null);
            }

            string xpath = "/" + root;  //这是新节点的父节点路径/Forms
            string nodename = "param"; //这是新节点名称,在父节点下新增
            string nodetext = paramname;
            bool isSuccess = XMLHelper.CreateOrUpdateXmlNodeByXPath(xmlparamFileName, xpath, nodename, paramvalues, "Name", nodetext);
        }
        private static string getvalues(string paramname)
        {
            string str = string.Empty;
            //获取xml参数文档
            if (System.IO.File.Exists(xmlparamFileName))
            {
                string xpath = "/params/param";
                str = XMLHelper.GetXmlByAttribute(xmlparamFileName, xpath, "Name", paramname);
            }
            return str;
        }
        #endregion
    }
}
View Code

 

界面调用 

保存参数

       private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            FormHelper.SetFormParam(this);
        }

回读参数

        private void Form1_Load(object sender, EventArgs e)
        {
            FormHelper.LoadFormParam(this);
        }

xml 文档

<?xml version="1.0" encoding="utf-8"?>
<Forms>
  <FormName Name="测试">
    <parm>comboBox1$2|checkBox1$True|textBox3$pantext|textBox2$sfafas|textBox1$123</parm>
  </FormName>
  <FormName Name="Form1">
    <parm>textBox3$pantext|textBox2$sfafas|textBox1$123</parm>
  </FormName>
</Forms>

测试界面

C# winform窗体简单保存界面控件参数到xml C# winform窗体简单保存界面控件参数到xml

只做了TextBox、CheckBox、ComboBox参数保存 如需增加自行修改FormHelper里的GetParam和SetParam方法

 

单个参数保存

示例

   FormHelper.SetValue("132", "125646546793");
   FormHelper.SetValue("", 45678.012);

   double d = FormHelper.GetDoubleValue("");
   int a = FormHelper.GetIntValue("132",4566);
   bool b = FormHelper.GetBoolValue("dsfs");

生成的xml文档

<?xml version="1.0" encoding="utf-8"?>
<params>
  <param Name="132">12564654679879463</param>
  <param Name="">45678.012</param>
</params>

C# winform窗体简单保存界面控件参数到xml

上一篇:C语言中 预定义的一些特殊用法


下一篇:#if,#ifdef,#ifndef的区别