C#XmlHelper幫助類操作Xml文件的通用方法彙總

追逐時光者發表於2022-03-28

前言

  該篇文章主要總結的是自己平時工作中使用頻率比較高的Xml文件操作的一些常用方法和收集網上寫的比較好的一些通用Xml文件操作的方法(主要包括Xml序列化和反序列化,Xml檔案讀取,Xml文件節點內容增刪改的一些通過方法)。當然可能還有很多方法會漏了,假如各位同學好的方法可以在文末留言,我會統一收集起來。

C#XML基礎入門

https://www.cnblogs.com/Can-daydayup/p/16036872.html?

Xml反序列化為物件

 #region Xml反序列化為物件

        /// <summary>
        /// Xml反序列化為指定模型物件
        /// </summary>
        /// <typeparam name="T">物件型別</typeparam>
        /// <param name="xmlContent">Xml內容</param>
        /// <param name="isThrowException">是否丟擲異常</param>
        /// <returns></returns>
        public static T XmlConvertToModel<T>(string xmlContent, bool isThrowException = false) where T : class
        {
            StringReader stringReader = null;
            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                stringReader = new StringReader(xmlContent);
                return (T)xmlSerializer.Deserialize(stringReader);
            }
            catch (Exception ex)
            {
                if (isThrowException)
                {
                    throw ex;
                }
                return null;
            }
            finally
            {
                stringReader?.Dispose();
            }
        }

        /// <summary>     
        /// 讀取Xml檔案內容反序列化為指定的物件  
        /// </summary>    
        /// <param name="filePath">Xml檔案的位置(絕對路徑)</param>  
        /// <returns></returns>    
        public static T DeserializeFromXml<T>(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                    throw new ArgumentNullException(filePath + " not Exists");
                using (StreamReader reader = new StreamReader(filePath))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(T));
                    T ret = (T)xs.Deserialize(reader);
                    return ret;
                }
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }

        #endregion

物件序列化為Xml

 #region 物件序列化為Xml

        /// <summary>
        /// 物件序列化為Xml
        /// </summary>
        /// <param name="obj">物件</param>
        /// <param name="isThrowException">是否丟擲異常</param>
        /// <returns></returns>
        public static string ObjectSerializerXml<T>(T obj, bool isThrowException = false)
        {
            if (obj == null)
            {
                return string.Empty;
            }

            try
            {
                using (StringWriter sw = new StringWriter())
                {
                    Type t = obj.GetType();
                    //強制指定名稱空間,覆蓋預設的名稱空間  
                    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                    //在Xml序列化時去除預設名稱空間xmlns:xsd和xmlns:xsi
                    namespaces.Add(string.Empty, string.Empty);
                    XmlSerializer serializer = new XmlSerializer(obj.GetType());
                    //序列化時增加namespaces
                    serializer.Serialize(sw, obj, namespaces);
                    sw.Close();

                    string replaceStr = sw.ToString().Replace(@"<?xml version=""1.0"" encoding=""utf-16""?>", "");
                    return replaceStr;
                }
            }
            catch (Exception ex)
            {
                if (isThrowException)
                {
                    throw ex;
                }
                return string.Empty;
            }

        }

        #endregion

Xml字元處理

  #region Xml字元處理

        /// <summary>
        /// 特殊符號轉換為轉義字元
        /// </summary>
        /// <param name="xmlStr"></param>
        /// <returns></returns>
        public string XmlSpecialSymbolConvert(string xmlStr)
        {
            return xmlStr.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\'", "&apos;").Replace("\"", "&quot;");
        }

        #endregion

建立Xml文件

#region 建立Xml文件

        /// <summary>
        /// 建立Xml文件
        /// </summary>
        /// <param name="saveFilePath">檔案儲存位置</param>
        public void CreateXmlDocument(string saveFilePath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            //建立型別宣告節點  
            XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
            xmlDoc.AppendChild(node);
            //建立Xml根節點
            XmlNode root = xmlDoc.CreateElement("books");
            xmlDoc.AppendChild(root);

            XmlNode root1 = xmlDoc.CreateElement("book");
            root.AppendChild(root1);

            //建立子節點
            CreateNode(xmlDoc, root1, "author", "追逐時光者");
            CreateNode(xmlDoc, root1, "title", "XML學習教程");
            CreateNode(xmlDoc, root1, "publisher", "時光出版社");

            //將檔案儲存到指定位置
            xmlDoc.Save(saveFilePath/*"D://xmlSampleCreateFile.xml"*/);
        }

        /// <summary>    
        /// 建立節點    
        /// </summary>    
        /// <param name="xmlDoc">xml文件</param>    
        /// <param name="parentNode">Xml父節點</param>    
        /// <param name="name">節點名</param>    
        /// <param name="value">節點值</param>    
        ///   
        public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
        {
            //建立對應Xml節點元素
            XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
            node.InnerText = value;
            parentNode.AppendChild(node);
        }

        #endregion

Xml資料讀取

#region Xml資料讀取

        /// <summary>
        /// 讀取Xml指定節點中的資料
        /// </summary>
        /// <param name="filePath">Xml文件路徑</param>
        /// <param name="node">節點</param>
        /// <param name="attribute">讀取資料的屬性名</param>
        /// <returns>string</returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.XmlReadNodeAttributeValue(path, "/books/book", "author")
         ************************************************/
        public static string XmlReadNodeAttributeValue(string filePath, string node, string attribute)
        {
            string value = "";
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filePath);
                XmlNode xmlNode = doc.SelectSingleNode(node);
                value = (attribute.Equals("") ? xmlNode.InnerText : xmlNode.Attributes[attribute].Value);
            }
            catch { }
            return value;
        }


        /// <summary>
        /// 獲得xml檔案中指定節點的節點資料
        /// </summary>
        /// <param name="filePath">Xml文件路徑</param>
        /// <param name="nodeName">節點名</param>
        /// <returns></returns>
        public static string GetNodeInfoByNodeName(string filePath, string nodeName)
        {
            string XmlString = string.Empty;
            XmlDocument xml = new XmlDocument();
            xml.Load(filePath);
            XmlElement root = xml.DocumentElement;
            XmlNode node = root.SelectSingleNode("//" + nodeName);
            if (node != null)
            {
                XmlString = node.InnerText;
            }
            return XmlString;
        }

        /// <summary>
        /// 獲取某一節點的所有孩子節點的值
        /// </summary>
        /// <param name="node">要查詢的節點</param>
        /// <param name="filePath">Xml文件路徑</param>
        public string[] ReadAllChildallValue(string node, string filePath)
        {
            int i = 0;
            string[] str = { };
            XmlDocument doc = new XmlDocument();
            doc.Load(filePath);
            XmlNode xn = doc.SelectSingleNode(node);
            XmlNodeList nodelist = xn.ChildNodes;  //得到該節點的子節點
            if (nodelist.Count > 0)
            {
                str = new string[nodelist.Count];
                foreach (XmlElement el in nodelist)//讀元素值
                {
                    str[i] = el.Value;
                    i++;
                }
            }
            return str;
        }

        /// <summary>
        /// 獲取某一節點的所有孩子節點的值
        /// </summary>
        /// <param name="node">要查詢的節點</param>
        /// <param name="filePath">Xml文件路徑</param>
        public XmlNodeList ReadAllChild(string node, string filePath)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(filePath);
            XmlNode xn = doc.SelectSingleNode(node);
            XmlNodeList nodelist = xn.ChildNodes;  //得到該節點的子節點
            return nodelist;
        }

        #endregion

Xml插入資料

#region Xml插入資料

        /// <summary>
        /// Xml指定節點元素屬性插入資料
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="node">節點</param>
        /// <param name="element">元素名</param>
        /// <param name="attribute">屬性名</param>
        /// <param name="value">屬性資料</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.XmlInsertValue(path, "/books", "book", "author", "Value")
         ************************************************/
        public static void XmlInsertValue(string path, string node, string element, string attribute, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xmlNode = doc.SelectSingleNode(node);
                if (element.Equals(""))
                {
                    if (!attribute.Equals(""))
                    {
                        XmlElement xe = (XmlElement)xmlNode;
                        xe.SetAttribute(attribute, value);
                    }
                }
                else
                {
                    XmlElement xe = doc.CreateElement(element);
                    if (attribute.Equals(""))
                        xe.InnerText = value;
                    else
                        xe.SetAttribute(attribute, value);
                    //新增新增的節點
                    xmlNode.AppendChild(xe);
                }

                //儲存Xml文件
                doc.Save(path);
            }
            catch { }
        }

        #endregion

Xml修改資料

#region Xml修改資料

        /// <summary>
        /// Xml指定節點元素屬性修改資料
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="node">節點</param>
        /// <param name="attribute">屬性名</param>
        /// <param name="value">屬性資料</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.XmlUpdateValue(path, "/books", "book","author","Value")
         ************************************************/
        public static void XmlUpdateValue(string path, string node, string attribute, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xmlNode = doc.SelectSingleNode(node);
                XmlElement xmlElement = (XmlElement)xmlNode;
                if (attribute.Equals(""))
                    xmlElement.InnerText = value;
                else
                    xmlElement.SetAttribute(attribute, value);

                //儲存Xml文件
                doc.Save(path);
            }
            catch { }
        }


        #endregion

Xml刪除資料

 #region Xml刪除資料

        /// <summary>
        /// 刪除資料
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="node">節點</param>
        /// <param name="attribute">屬性名</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.XmlDelete(path, "/books", "book")
         ************************************************/
        public static void XmlDelete(string path, string node, string attribute)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xn = doc.SelectSingleNode(node);
                XmlElement xe = (XmlElement)xn;
                if (attribute.Equals(""))
                    xn.ParentNode.RemoveChild(xn);
                else
                    xe.RemoveAttribute(attribute);
                doc.Save(path);
            }
            catch { }
        }

        #endregion

完整的XmlHelper幫助類

 注意:有些方法不能保證百分之百沒有問題的,假如有問題可以留言給我,我會驗證並立即修改。

    /// <summary>
    /// Xml幫助類
    /// </summary>
    public class XMLHelper
    {
        #region Xml反序列化為物件

        /// <summary>
        /// Xml反序列化為指定模型物件
        /// </summary>
        /// <typeparam name="T">物件型別</typeparam>
        /// <param name="xmlContent">Xml內容</param>
        /// <param name="isThrowException">是否丟擲異常</param>
        /// <returns></returns>
        public static T XmlConvertToModel<T>(string xmlContent, bool isThrowException = false) where T : class
        {
            StringReader stringReader = null;
            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
                stringReader = new StringReader(xmlContent);
                return (T)xmlSerializer.Deserialize(stringReader);
            }
            catch (Exception ex)
            {
                if (isThrowException)
                {
                    throw ex;
                }
                return null;
            }
            finally
            {
                stringReader?.Dispose();
            }
        }

        /// <summary>     
        /// 讀取Xml檔案內容反序列化為指定的物件  
        /// </summary>    
        /// <param name="filePath">Xml檔案的位置(絕對路徑)</param>  
        /// <returns></returns>    
        public static T DeserializeFromXml<T>(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                    throw new ArgumentNullException(filePath + " not Exists");
                using (StreamReader reader = new StreamReader(filePath))
                {
                    XmlSerializer xs = new XmlSerializer(typeof(T));
                    T ret = (T)xs.Deserialize(reader);
                    return ret;
                }
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }

        #endregion

        #region 物件序列化為Xml

        /// <summary>
        /// 物件序列化為Xml
        /// </summary>
        /// <param name="obj">物件</param>
        /// <param name="isThrowException">是否丟擲異常</param>
        /// <returns></returns>
        public static string ObjectSerializerXml<T>(T obj, bool isThrowException = false)
        {
            if (obj == null)
            {
                return string.Empty;
            }

            try
            {
                using (StringWriter sw = new StringWriter())
                {
                    Type t = obj.GetType();
                    //強制指定名稱空間,覆蓋預設的名稱空間  
                    XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                    //在Xml序列化時去除預設名稱空間xmlns:xsd和xmlns:xsi
                    namespaces.Add(string.Empty, string.Empty);
                    XmlSerializer serializer = new XmlSerializer(obj.GetType());
                    //序列化時增加namespaces
                    serializer.Serialize(sw, obj, namespaces);
                    sw.Close();

                    string replaceStr = sw.ToString().Replace(@"<?xml version=""1.0"" encoding=""utf-16""?>", "");
                    return replaceStr;
                }
            }
            catch (Exception ex)
            {
                if (isThrowException)
                {
                    throw ex;
                }
                return string.Empty;
            }

        }

        #endregion

        #region Xml字元處理

        /// <summary>
        /// 特殊符號轉換為轉義字元
        /// </summary>
        /// <param name="xmlStr"></param>
        /// <returns></returns>
        public string XmlSpecialSymbolConvert(string xmlStr)
        {
            return xmlStr.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\'", "&apos;").Replace("\"", "&quot;");
        }

        #endregion

        #region 建立Xml文件

        /// <summary>
        /// 建立Xml文件
        /// </summary>
        /// <param name="saveFilePath">檔案儲存位置</param>
        public void CreateXmlDocument(string saveFilePath)
        {
            XmlDocument xmlDoc = new XmlDocument();
            //建立型別宣告節點  
            XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
            xmlDoc.AppendChild(node);
            //建立Xml根節點
            XmlNode root = xmlDoc.CreateElement("books");
            xmlDoc.AppendChild(root);

            XmlNode root1 = xmlDoc.CreateElement("book");
            root.AppendChild(root1);

            //建立子節點
            CreateNode(xmlDoc, root1, "author", "追逐時光者");
            CreateNode(xmlDoc, root1, "title", "XML學習教程");
            CreateNode(xmlDoc, root1, "publisher", "時光出版社");

            //將檔案儲存到指定位置
            xmlDoc.Save(saveFilePath/*"D://xmlSampleCreateFile.xml"*/);
        }

        /// <summary>    
        /// 建立節點    
        /// </summary>    
        /// <param name="xmlDoc">xml文件</param>    
        /// <param name="parentNode">Xml父節點</param>    
        /// <param name="name">節點名</param>    
        /// <param name="value">節點值</param>    
        ///   
        public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
        {
            //建立對應Xml節點元素
            XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
            node.InnerText = value;
            parentNode.AppendChild(node);
        }

        #endregion

        #region Xml資料讀取

        /// <summary>
        /// 讀取Xml指定節點中的資料
        /// </summary>
        /// <param name="filePath">Xml文件路徑</param>
        /// <param name="node">節點</param>
        /// <param name="attribute">讀取資料的屬性名</param>
        /// <returns>string</returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.XmlReadNodeAttributeValue(path, "/books/book", "author")
         ************************************************/
        public static string XmlReadNodeAttributeValue(string filePath, string node, string attribute)
        {
            string value = "";
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filePath);
                XmlNode xmlNode = doc.SelectSingleNode(node);
                value = (attribute.Equals("") ? xmlNode.InnerText : xmlNode.Attributes[attribute].Value);
            }
            catch { }
            return value;
        }


        /// <summary>
        /// 獲得xml檔案中指定節點的節點資料
        /// </summary>
        /// <param name="filePath">Xml文件路徑</param>
        /// <param name="nodeName">節點名</param>
        /// <returns></returns>
        public static string GetNodeInfoByNodeName(string filePath, string nodeName)
        {
            string XmlString = string.Empty;
            XmlDocument xml = new XmlDocument();
            xml.Load(filePath);
            XmlElement root = xml.DocumentElement;
            XmlNode node = root.SelectSingleNode("//" + nodeName);
            if (node != null)
            {
                XmlString = node.InnerText;
            }
            return XmlString;
        }

        /// <summary>
        /// 獲取某一節點的所有孩子節點的值
        /// </summary>
        /// <param name="node">要查詢的節點</param>
        /// <param name="filePath">Xml文件路徑</param>
        public string[] ReadAllChildallValue(string node, string filePath)
        {
            int i = 0;
            string[] str = { };
            XmlDocument doc = new XmlDocument();
            doc.Load(filePath);
            XmlNode xn = doc.SelectSingleNode(node);
            XmlNodeList nodelist = xn.ChildNodes;  //得到該節點的子節點
            if (nodelist.Count > 0)
            {
                str = new string[nodelist.Count];
                foreach (XmlElement el in nodelist)//讀元素值
                {
                    str[i] = el.Value;
                    i++;
                }
            }
            return str;
        }

        /// <summary>
        /// 獲取某一節點的所有孩子節點的值
        /// </summary>
        /// <param name="node">要查詢的節點</param>
        /// <param name="filePath">Xml文件路徑</param>
        public XmlNodeList ReadAllChild(string node, string filePath)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(filePath);
            XmlNode xn = doc.SelectSingleNode(node);
            XmlNodeList nodelist = xn.ChildNodes;  //得到該節點的子節點
            return nodelist;
        }

        #endregion

        #region Xml插入資料

        /// <summary>
        /// Xml指定節點元素屬性插入資料
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="node">節點</param>
        /// <param name="element">元素名</param>
        /// <param name="attribute">屬性名</param>
        /// <param name="value">屬性資料</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.XmlInsertValue(path, "/books", "book", "author", "Value")
         ************************************************/
        public static void XmlInsertValue(string path, string node, string element, string attribute, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xmlNode = doc.SelectSingleNode(node);
                if (element.Equals(""))
                {
                    if (!attribute.Equals(""))
                    {
                        XmlElement xe = (XmlElement)xmlNode;
                        xe.SetAttribute(attribute, value);
                    }
                }
                else
                {
                    XmlElement xe = doc.CreateElement(element);
                    if (attribute.Equals(""))
                        xe.InnerText = value;
                    else
                        xe.SetAttribute(attribute, value);
                    //新增新增的節點
                    xmlNode.AppendChild(xe);
                }

                //儲存Xml文件
                doc.Save(path);
            }
            catch { }
        }

        #endregion

        #region Xml修改資料

        /// <summary>
        /// Xml指定節點元素屬性修改資料
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="node">節點</param>
        /// <param name="attribute">屬性名</param>
        /// <param name="value">屬性資料</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.XmlUpdateValue(path, "/books", "book","author","Value")
         ************************************************/
        public static void XmlUpdateValue(string path, string node, string attribute, string value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xmlNode = doc.SelectSingleNode(node);
                XmlElement xmlElement = (XmlElement)xmlNode;
                if (attribute.Equals(""))
                    xmlElement.InnerText = value;
                else
                    xmlElement.SetAttribute(attribute, value);

                //儲存Xml文件
                doc.Save(path);
            }
            catch { }
        }


        #endregion

        #region Xml刪除資料

        /// <summary>
        /// 刪除資料
        /// </summary>
        /// <param name="path">路徑</param>
        /// <param name="node">節點</param>
        /// <param name="attribute">屬性名</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.XmlDelete(path, "/books", "book")
         ************************************************/
        public static void XmlDelete(string path, string node, string attribute)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNode xn = doc.SelectSingleNode(node);
                XmlElement xe = (XmlElement)xn;
                if (attribute.Equals(""))
                    xn.ParentNode.RemoveChild(xn);
                else
                    xe.RemoveAttribute(attribute);
                doc.Save(path);
            }
            catch { }
        }

        #endregion
    }

 

相關文章