XML文件操作函数

来源:互联网 发布:淘宝云客服判断题 编辑:程序博客网 时间:2024/06/10 00:49

实现对XML文件读写操作及节点数据更新,序列化及反序列化操作

using System;using System.Collections.Generic;using System.Text;using System.Threading.Tasks;using System.Xml;using System.Xml.Serialization;using System.IO;using System.Diagnostics;using System.Runtime.Serialization.Formatters.Binary;  public class XmlUnit    {        public static string GetFormatTime(DateTime m_DateTime)        {            string m_Date = m_DateTime.ToString("yyyy-MM-dd");   // 2015-01-22            string m_Time = m_DateTime.TimeOfDay.ToString();     // 15:14:35.4412864            string m_xmlTime = m_Date + "T" + m_Time + "+08:00"; //"2015-12-21T21:42:34.7998046+08:00"              return m_xmlTime;        }        //============================================================================================        //============================================================================================        #region 更新节点属性        /// <summary> 更新第二级节点属性内容 </summary>        public static bool ModifyXmlData(string xmlFilePath, string RootNode, string FirstNode, string attribute, string strData)        {            try            {                XmlDocument m_XmlDoc = new XmlDocument();                m_XmlDoc.Load(xmlFilePath);                XmlNode m_RootNode = m_XmlDoc.SelectSingleNode(RootNode);                XmlNodeList m_FirstLevelNodeList = m_RootNode.ChildNodes;                foreach (XmlNode m_FirstNode in m_FirstLevelNodeList)                {                    if (m_FirstNode.Name == FirstNode)                    {                        XmlAttributeCollection attributeCol = m_FirstNode.Attributes;   //获得该节点的属性集合                        foreach (XmlAttribute attri in attributeCol)                        {                            if (attri.Name == attribute)                            {                                m_FirstNode.Attributes[attribute].Value = strData;                                m_XmlDoc.Save(xmlFilePath);                                  return true;                            }                        }                    }                }                return false;            }            catch (Exception ex)            {                Trace.WriteLine(ex.ToString());                return false;            }        }        /// <summary> 更新第三级节点属性内容 </summary>        public static bool ModifyXmlData(string xmlFilePath, string RootNode, string FirstNode, string SecondNode, string attribute, string strData)        {            try            {                XmlDocument m_XmlDoc = new XmlDocument();                m_XmlDoc.Load(xmlFilePath);                XmlNode m_NootNode = m_XmlDoc.SelectSingleNode(RootNode);                XmlNodeList m_FirstLevelNodeList = m_NootNode.ChildNodes;                foreach (XmlNode m_FirstNode in m_FirstLevelNodeList)                {                    if (m_FirstNode.Name == FirstNode)                    {                        #region 第二级元素                        XmlNodeList m_SecondLevelNodeList = m_FirstNode.ChildNodes;                        foreach (XmlNode m_SecondNode in m_SecondLevelNodeList)                        {                            if (m_SecondNode.Name == SecondNode)                            {                                #region 第二级元素属性                                XmlAttributeCollection m_AttributeCol = m_SecondNode.Attributes;   //获得该节点的属性集合                                foreach (XmlAttribute m_Attri in m_AttributeCol)                                {                                    if (m_Attri.Name == attribute)                                    {                                        m_SecondNode.Attributes[attribute].Value = strData;                                        m_XmlDoc.Save(xmlFilePath);                                          return true;                                    }                                }                                #endregion                            }                        }                        #endregion                    }                }                return false;            }            catch (Exception ex)            {                Trace.WriteLine(ex.ToString());                return false;            }        }        /// <summary> 更新第四级节点属性内容 </summary>        public static bool ModifyXmlData(string xmlFilePath, string RootNode, string FirstNode, string SecondNode, string ThirdNode, string attribute, string strData)        {            try            {                XmlDocument m_XmlDoc = new XmlDocument();                m_XmlDoc.Load(xmlFilePath);                XmlNode m_NootNode = m_XmlDoc.SelectSingleNode(RootNode);                XmlNodeList m_FirstLevelNodeList = m_NootNode.ChildNodes;                foreach (XmlNode m_FirstNode in m_FirstLevelNodeList)                {                    if (m_FirstNode.Name == FirstNode)                    {                        #region 第二级元素                        XmlNodeList m_SecondLevelNodeList = m_FirstNode.ChildNodes;                        foreach (XmlNode m_SecondNode in m_SecondLevelNodeList)                        {                            if (m_SecondNode.Name == SecondNode)                            {                                #region 第三级元素                                XmlNodeList m_ThirdLevelNodeList = m_SecondNode.ChildNodes;                                foreach (XmlNode m_ThirdNode in m_ThirdLevelNodeList)                                {                                    if (m_ThirdNode.Name == ThirdNode)                                    {                                        #region 第三级元素属性                                        XmlAttributeCollection m_AttributeCol = m_ThirdNode.Attributes;   //获得该节点的属性集合                                        foreach (XmlAttribute m_Attri in m_AttributeCol)                                        {                                            if (m_Attri.Name == attribute)                                            {                                                m_ThirdNode.Attributes[attribute].Value = strData;                                                m_XmlDoc.Save(xmlFilePath);                                                return true;                                            }                                        }                                        #endregion                                    }                                }                                                              #endregion                                                           }                        }                        #endregion                    }                }                return false;            }            catch (Exception ex)            {                Trace.WriteLine(ex.ToString());                return false;            }        }        #endregion        //============================================================================================        //============================================================================================        #region 获取节点属性数据        public static bool GetXmlData(string xmlFilePath, string RootNode, string FirstNode, string attribute, out string strData)        {            strData = "";            try            {                                XmlDocument m_XmlDoc = new XmlDocument();                m_XmlDoc.Load(xmlFilePath);                XmlNode m_RootNode = m_XmlDoc.SelectSingleNode(RootNode);                XmlNodeList m_FirstLevelNodeList = m_RootNode.ChildNodes;                foreach (XmlNode m_FirstNode in m_FirstLevelNodeList)                {                    if (m_FirstNode.Name == FirstNode)                    {                        XmlAttributeCollection attributeCol = m_FirstNode.Attributes;   //获得该节点的属性集合                        foreach (XmlAttribute attri in attributeCol)                        {                            if (attri.Name == attribute)                            {                               strData= m_FirstNode.Attributes[attribute].Value  ;                                return true;                            }                        }                    }                }                return false;            }            catch (Exception ex)            {                Trace.WriteLine(ex.ToString());                return false;            }        }        public static bool GetXmlData(XmlDocument m_XmlDoc, string RootNode, string FirstNode, string attribute, out string strData)        {            strData = "";            try            {                XmlNode m_RootNode = m_XmlDoc.SelectSingleNode(RootNode);                XmlNodeList m_FirstLevelNodeList = m_RootNode.ChildNodes;                foreach (XmlNode m_FirstNode in m_FirstLevelNodeList)                {                    if (m_FirstNode.Name == FirstNode)                    {                        XmlAttributeCollection attributeCol = m_FirstNode.Attributes;   //获得该节点的属性集合                        foreach (XmlAttribute attri in attributeCol)                        {                            if (attri.Name == attribute)                            {                                strData = m_FirstNode.Attributes[attribute].Value;                                return true;                            }                        }                    }                }                return false;            }            catch (Exception ex)            {                Trace.WriteLine(ex.ToString());                return false;            }        }        public static bool GetXmlData(string xmlFilePath, string RootNode, string FirstNode, string SecondNode, string attribute, out string strData)        {            strData = "";            try            {                XmlDocument m_XmlDoc = new XmlDocument();                m_XmlDoc.Load(xmlFilePath);                XmlNode m_NootNode = m_XmlDoc.SelectSingleNode(RootNode);                XmlNodeList m_FirstLevelNodeList = m_NootNode.ChildNodes;                foreach (XmlNode m_FirstNode in m_FirstLevelNodeList)                {                    if (m_FirstNode.Name == FirstNode)                    {                        #region 第二级元素                        XmlNodeList m_SecondLevelNodeList = m_NootNode.ChildNodes;                        foreach (XmlNode m_SecondNode in m_SecondLevelNodeList)                        {                            if (m_SecondNode.Name == SecondNode)                            {                                XmlAttributeCollection m_AttributeCol = m_SecondNode.Attributes;   //获得该节点的属性集合                                foreach (XmlAttribute m_Attri in m_AttributeCol)                                {                                    if (m_Attri.Name == attribute)                                    {                                        strData = m_SecondNode.Attributes[attribute].Value;                                        return true;                                    }                                }                            }                        }                        #endregion                    }                }                return false;            }            catch (Exception ex)            {                Console.WriteLine(ex.ToString());                return false;            }        }        public static string GetXmlAttributeValue(XmlNode m_Node, string AttrName)        {            foreach (XmlAttribute attri in m_Node.Attributes)            {                if (attri.Name == AttrName)                {                    return attri.Value;                }            }            return null;        }        #endregion        //============================================================================================        //============================================================================================        #region 添加节点        public static bool AddXmlElement(XmlDocument m_XmlDoc, XmlNode ParentNode, string NewNode, string AttrName, string strSetValue)        {            try            {                XmlElement m_Node = m_XmlDoc.CreateElement(NewNode);                m_Node.SetAttribute(AttrName, strSetValue);                ParentNode.AppendChild(m_Node);                return true;            }            catch { }            return false;        }        private static void AddXmlElement(string xmlFilePath,string RootNode,XmlElement xmlElement)        {            try            {                XmlDocument m_XmlDoc = new XmlDocument();                m_XmlDoc.Load(xmlFilePath);                XmlNode m_RootNode = m_XmlDoc.SelectSingleNode(RootNode);                m_RootNode.AppendChild(xmlElement);                m_XmlDoc.Save(xmlFilePath);            }            catch (Exception ex)            {                Trace.WriteLine(ex.ToString());            }        }        private static void AddXmlElement(string xmlFilePath, string RootNode, string FirstNode, XmlElement newElement)        {            try            {                XmlDocument m_XmlDoc = new XmlDocument();                m_XmlDoc.Load(xmlFilePath);                XmlNode m_RootNode = m_XmlDoc.SelectSingleNode(RootNode);                foreach (XmlNode m_FirstNode in m_RootNode.ChildNodes)                {                    if (m_FirstNode.Name == FirstNode)                    {                        m_FirstNode.AppendChild(newElement);                        m_XmlDoc.Save(xmlFilePath);                    }                }                           }            catch (Exception ex)            {                Trace.WriteLine(ex.ToString());            }        }        #endregion        private static void DeleteXmlElement(string xmlFilePath)        {            try            {                XmlDocument m_XmlDoc = new XmlDocument();                m_XmlDoc.Load(xmlFilePath);                foreach (XmlNode node in m_XmlDoc.FirstChild.ChildNodes)                {                                      XmlNode lastNode = node.LastChild; //记录该节点下的最后一个子节点(简称:最后子节点)                                        lastNode.RemoveAll();              //删除最后子节点下的左右子节点                    node.RemoveChild(lastNode);        //删除最后子节点                }                m_XmlDoc.Save(xmlFilePath);            }            catch (Exception ex)            {                Trace.WriteLine(ex.ToString());            }        }        //============================================================================================        //============================================================================================        //文件序列化为XML字节数组        public static byte[] SerializeToXmlBytes(object objectToSerialize)        {            //实例化内存流用来存储序列化的信息            MemoryStream memoryStream = new MemoryStream();            XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType());            xmlSerializer.Serialize(memoryStream, objectToSerialize);            return memoryStream.ToArray();        }        //字节数组 反序列化为文件         public static object DeSerializeFromXmlBytes(byte[] xmlStream)        {            MemoryStream memoryStream = new MemoryStream(xmlStream);            XmlSerializer ser = new XmlSerializer(typeof(XmlDocument));            return ser.Deserialize(memoryStream);        }        //XML字符串 反序列化为文件         public static object DeSerializeFromXmlString(System.Type typeToDeserialize, string xmlString)        {            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(xmlString);            MemoryStream memoryStream = new MemoryStream(bytes);            XmlSerializer xmlSerializer = new XmlSerializer(typeToDeserialize);            return xmlSerializer.Deserialize(memoryStream);        }        //文件序列化为XML字符串        public static string SerializeToXmlString(object obj)        {            XmlSerializer serializer = new XmlSerializer(obj.GetType());            StringWriter writer = new StringWriter();            serializer.Serialize(writer, obj);            return writer.GetStringBuilder().ToString();        }        //文件序列化为XML字符串        public static string SerializeToXmlString2(object objectToSerialize)        {            MemoryStream memoryStream = new MemoryStream();            XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType());            xmlSerializer.Serialize(memoryStream, objectToSerialize);            ASCIIEncoding ascii = new ASCIIEncoding();            return ascii.GetString(memoryStream.ToArray());        }        //文件序列化为XML字符串(utf-8)        public static string SerializeToXmlString_utf8(object objectToSerialize)        {            //实例化内存流用来存储序列化的信息            MemoryStream memoryStream = new MemoryStream();            XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType());            xmlSerializer.Serialize(memoryStream, objectToSerialize);            byte[] data = memoryStream.ToArray();            return System.Text.Encoding.UTF8.GetString(data);// 将接受到的字节数据转化成字符串;        }        //==========================================================================================        public static ItemType Deserialize<ItemType>(string strXml)        {            return Deserialize<ItemType>(new StringReader(strXml));        }        public static ItemType Deserialize<ItemType>(TextReader trReader)        {            XmlSerializer serializer = new XmlSerializer(typeof(ItemType));            return (ItemType)serializer.Deserialize(trReader);        }        //public static string Base64Serialize(object obj)        //{        //    if (obj == null) return string.Empty;        //    else        //    {        //        try        //        {        //            string resultValue = SerializeToXmlString(obj);        //            return Base64Util.StringToBase64(resultValue);        //        }        //        catch        //        {        //            return string.Empty;        //        }        //    }        //}        //public static ItemType Base64Deserialize<ItemType>(string strXmlBase64)        //{        //    if (String.IsNullOrEmpty(strXmlBase64)) return default(ItemType);        //    else        //    {        //        try        //        {        //            string xmlString = Base64Util.Base64ToString(strXmlBase64);        //            return Deserialize<ItemType>(xmlString);        //        }        //        catch        //        {        //            return default(ItemType);        //        }        //    }        //}        public static string BinarySerializer(object obj)        {            MemoryStream stream = new MemoryStream();            BinaryFormatter formatter = new BinaryFormatter();            formatter.Serialize(stream, obj);            string fontString = Convert.ToBase64String(stream.ToArray());            return fontString;        }        public static object BinaryDeserialize(string stringXMLBinary)        {            BinaryFormatter formatter = new BinaryFormatter();            try            {                byte[] bytes = Convert.FromBase64String(stringXMLBinary);                MemoryStream stream = new MemoryStream(bytes);                return formatter.Deserialize(stream);            }            catch            {                return null;            }        }    }
原创粉丝点击