XmlHelper 通用类

Posted wesson2019-blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了XmlHelper 通用类相关的知识,希望对你有一定的参考价值。

    /// <summary>
    /// 提供对XML数据的读写
    /// </summary>
    public sealed class XmlHelper
    {        
        /// <summary>
        /// 声明一个XmlDocument空对象
        /// </summary>
        private XmlDocument _xmlDoc = new XmlDocument();
        /// <summary>
        /// 构造函数,导入Xml文件
        /// </summary>
        /// <param name="xmlFile">文件绝对路径</param>
        public XmlHelper(string xmlFile)
        {
            try
            {
                _xmlDoc.Load(xmlFile);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        ~XmlHelper()
        {
            _xmlDoc = null; // 释放XmlDocument对象
        }
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="filePath">文件绝对路径</param>
        public void Save(string filePath)
        {
            try
            {
                _xmlDoc.Save(filePath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 根据Xml文件的节点路径,返回一个DataSet数据集
        /// </summary>
        /// <param name="xmlPathNode">Xml文件的某个节点</param>
        /// <returns></returns>
        public DataSet GetDataSet(string xmlPathNode)
        {
            DataSet ds = new DataSet();
            try
            {
                System.IO.StringReader read = new System.IO.StringReader(_xmlDoc.SelectSingleNode(xmlPathNode).OuterXml);
                ds.ReadXml(read);
                read.Close();
            }
            catch (Exception ex)
            {
                string err = ex.Message;
            }
            return ds;
        }
        /// <summary>
        /// 属性查询,返回属性值
        /// </summary>
        /// <param name="xmlPathNode">属性所在的节点</param>
        /// <param name="attributeName">属性名</param>
        /// <returns></returns>
        public string GetAttributeValue(string xmlPathNode, string attributeName)
        {
            string rlt = string.Empty;
            try
            {
                rlt = _xmlDoc.SelectSingleNode(xmlPathNode).Attributes[attributeName].Value;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
            }
            return rlt;
        }
        /// <summary>
        /// 节点查询,返回节点值
        /// </summary>
        /// <param name="xmlPathNode">节点的路径</param>
        /// <returns></returns>
        public string GetNodeText(string xmlPathNode)
        {
            string txt = _xmlDoc.SelectSingleNode(xmlPathNode).InnerText;
            if (null == txt || string.Empty == txt)
            {
                return string.Empty;
            }
            return txt;
        }
        /// <summary>
        /// 节点值查询判断
        /// </summary>
        /// <param name="xmlPathNode">父节点</param>
        /// <param name="index">节点索引</param>
        /// <param name="nodeText">节点值</param>
        /// <returns></returns>
        public bool IsValidNode(string xmlPathNode, int index, string nodeText)
        {
            try
            {
                XmlNodeList nodeList = _xmlDoc.SelectNodes(xmlPathNode);
                // 循环遍历节点,查询是否存在该节点
                for (int i = 0; i < nodeList.Count; i++)
                {
                    if (nodeText == nodeList[i].ChildNodes[index].InnerText)
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                string err = ex.Message;
            }
            return false;
        }
        /// <summary>
        /// 获取子节点个数
        /// </summary>
        /// <param name="xmlPathNode">父节点</param>
        /// <returns></returns>
        public int NodeCount(string xmlPathNode)
        {
            int rlt = 0;
            try
            {
                rlt = _xmlDoc.SelectSingleNode(xmlPathNode).ChildNodes.Count;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                rlt = 0;
            }
            return rlt;
        }
        /// <summary>
        /// 更新一个节点的内容
        /// </summary>
        /// <param name="xmlPathNode">节点的路径</param>
        /// <param name="nodeContent">新的节点值</param>
        /// <returns></returns>
        public bool UpdateNode(string xmlPathNode, string nodeContent)
        {
            try
            {
                _xmlDoc.SelectSingleNode(xmlPathNode).InnerText = nodeContent;
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }
        /// <summary>
        /// 更新N个节点值
        /// </summary>
        /// <param name="xmlParentNode">父节点</param>
        /// <param name="xmlNodes">子节点</param>
        /// <param name="nodeContents">子节点内容</param>
        /// <returns></returns>
        public bool UpdateNode(string xmlParentNode, string[] xmlNodes, string[] nodeContents)
        {
            try
            {
                // 根据节点数组循环修改节点值
                for (int i = 0; i < xmlNodes.Length; i++)
                {
                    _xmlDoc.SelectSingleNode(xmlParentNode + "/" + xmlNodes[i]).InnerText = nodeContents[i];
                }
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }
        /// <summary>
        /// 修改属性
        /// </summary>
        /// <param name="xmlPathNode">属性所在的节点</param>
        /// <param name="attributeName">属性名</param>
        /// <param name="attributeValue">属性值</param>
        /// <returns></returns>
        public bool UpdateAttributeValue(string xmlPathNode, string attributeName, string attributeValue)
        {
            try
            {
                _xmlDoc.SelectSingleNode(xmlPathNode).Attributes[attributeName].Value = attributeValue;
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }
        /// <summary>
        /// 添加属性
        /// </summary>
        /// <param name="xmlPathNode">属性所在的节点</param>
        /// <param name="attributeName">属性名</param>
        /// <param name="attributeValue">属性值</param>
        /// <returns></returns>
        public bool InsertAttribute(string xmlPathNode, string attributeName, string attributeValue)
        {
            try
            {
                XmlElement element = (XmlElement)_xmlDoc.SelectSingleNode(xmlPathNode);
                element.SetAttribute(attributeName, attributeValue);
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }
        /// <summary>
        /// 插入一个节点,带N个子节点
        /// </summary>
        /// <param name="xmlPathNode">当前节点</param>
        /// <param name="nodeName">插入节点的名称</param>
        /// <param name="elementNames">子节点的名称数组</param>
        /// <param name="contents">子节点的内容数组</param>
        /// <returns></returns>
        public bool InsertNode(string xmlPathNode, string nodeName, string[] elementNames, string[] contents)
        {
            try
            {
                XmlNode node = _xmlDoc.SelectSingleNode(xmlPathNode);
                XmlElement childNode = _xmlDoc.CreateElement(nodeName);
                node.AppendChild(childNode);
                for (int i = 0; i < elementNames.Length; i++)
                {
                    XmlElement element = _xmlDoc.CreateElement(elementNames[i]);
                    element.InnerText = contents[i];
                    childNode.AppendChild(element);
                }
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }
        /// <summary>
        /// 删除一个节点
        /// </summary>
        /// <param name="xmlPathNode">节点的路径</param>
        /// <returns></returns>
        public bool DeleteNode(string xmlPathNode)
        {
            try
            {
                _xmlDoc.SelectSingleNode(xmlPathNode).ParentNode.RemoveChild(_xmlDoc.SelectSingleNode(xmlPathNode));
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }


        /// <summary>
        /// 将对象序列化成XML
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="hasNamespace">是否有Xml头部</param>
        /// <returns></returns>
        public static string Serialize(object obj, bool hasNamespace = false)
        {
            string xml = string.Empty;
            try
            {
                var sb = new StringBuilder();
                var xmlSettings = new XmlWriterSettings();
                xmlSettings.OmitXmlDeclaration = hasNamespace;
                // 换行缩进
                xmlSettings.Indent = true;
                xmlSettings.Encoding = System.Text.Encoding.Default;
                using (var xmlWriter = XmlWriter.Create(sb, xmlSettings))
                {
                    var xmlSerializer = new XmlSerializer(obj.GetType());
                    // 去除默认命名空间xmlns:xsd和xmlns:xsi
                    var xmlNampespace = new XmlSerializerNamespaces();
                    xmlNampespace.Add("", "");

                    if (hasNamespace)
                    {
                        xmlSerializer.Serialize(xmlWriter, obj);
                    }
                    else
                    {
                        xmlSerializer.Serialize(xmlWriter, obj, xmlNampespace);
                    }
                    xml = sb.ToString();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return xml;
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="xmlStr">xml字符串</param>
        /// <returns>反序列化模型</returns>
        public static T DeSerialize<T>(string xmlStr)
        {
            return (T)Deserialize(typeof(T), xmlStr);
        }
        private static object Deserialize(Type type, string xmlStr)
        {
            try
            {
                using (var sr = new StringReader(xmlStr))
                {
                    var serializer = new XmlSerializer(type);
                    return serializer.Deserialize(sr);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 将XML文本写入指定文件
        /// </summary>
        /// <param name="filePath">绝对路径</param>
        /// <param name="xmlStr">XML文本</param>
        /// <returns></returns>
        public static bool WriteXmlString(string filePath, string xmlStr)
        {
            try
            {
                File.WriteAllText(filePath, xmlStr);
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }
        /// <summary>
        /// 读取XML文本
        /// </summary>
        /// <param name="filePath">绝对路径</param>
        /// <returns></returns>
        public static string ReadXmlString(string filePath)
        {
            try
            {
                return File.ReadAllText(filePath, Encoding.Default);
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }            
        }

    }

Demo

以上是关于XmlHelper 通用类的主要内容,如果未能解决你的问题,请参考以下文章

XMLHelper

XMLHelper

XmlHelper

Eclipse 中的通用代码片段或模板

Android 逆向Android 逆向通用工具开发 ( Android 平台运行的 cmd 程序类型 | Android 平台运行的 cmd 程序编译选项 | 编译 cmd 可执行程序 )(代码片段

如何使用滚动片段容器实现通用布局?