• XML文件数据操作


    #region XML序列化文件和反序列化
    
            /// <summary>
            /// 通用类的保存函数,可以将已经声明过可序列化的类以文件方式保存起来。
            /// 保存格式分为 XML明文式和 二进制。
            /// 如果目标目录不存在,就自动创建目录。
            /// </summary>
            /// <typeparam name="T">要保存的类的类型</typeparam>
            /// <param name="tclass">要保存的类</param>
            /// <param name="sFilePath">要保存的文件完整路径,包括文件名。</param>
            /// <param name="bXmlOrBin">true=XML,false=Bin</param>
            /// <exception cref="System.Exception"></exception>
            public void Save<T>(T tclass, string sFilePath, bool bXmlOrBin)
            {
                //目录检查
                string sFolder = sFilePath.Substring(0, sFilePath.LastIndexOf("\"));
                if (!Directory.Exists(sFolder)) Directory.CreateDirectory(sFolder);
    
                using (FileStream fs = new FileStream(sFilePath, FileMode.Create, FileAccess.Write))
                {
                    if (bXmlOrBin)
                    {
                        using (MemoryStream stream = Serialize<T>(tclass, bXmlOrBin))
                        {
                            stream.WriteTo(fs);
                            stream.Close();
                        }
                    }
                    else
                    {
                        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = null;
                        bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        bf.Serialize(fs, bXmlOrBin);
                    }
                    fs.Close();
                }
            }
    
            /// <summary>
            /// 从文件加载保存的信息,然后反序列化并返回保存的信息。
            /// 如果要读取的文件不存在会引发异常。
            /// </summary>
            /// <typeparam name="T">类型</typeparam>
            /// <param name="tclass">要返回的类,失败返回默认</param>
            /// <param name="sFilePath">文件路径</param>
            /// <param name="bXmlOrBin">true=XML,false=Bin</param>
            /// <exception cref="System.Exception"></exception>
            /// <exception cref="System.IO.IOException">文件不存在</exception>
            public void Load<T>(out T tclass, string sFilePath, bool bXmlOrBin)
            {
                if (!File.Exists(sFilePath))
                {
                    tclass = default(T);
                    return;
                    //throw new IOException("要访问的文件不存在。");
                }
                using (FileStream fs = new FileStream(sFilePath, FileMode.Open, FileAccess.Read))
                {
                    tclass = Deserialize<T>(fs, bXmlOrBin);
                    fs.Close();
                }
            }
    
            /// <summary>
            /// 将传入的某个模型序列化,并返回其数据量,用于保存到文件里面。
            /// 提供序列化到XML或二进制。
            /// </summary>
            /// <typeparam name="T">类的类型</typeparam>
            /// <param name="model">要序列化的模型</param>
            /// <param name="bXmlOrBin">true=xml序列化,false=二进制序列化</param>
            /// <returns></returns>
            /// <exception cref="System.Exception"></exception>
            public MemoryStream Serialize<T>(T model, bool bXmlOrBin = true)
            {
                MemoryStream stream = new MemoryStream();
                if (bXmlOrBin)
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(T));
                    serializer.Serialize(stream, model);
                }
                else
                {
                    var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    bf.Serialize(stream, model);
                }
                stream.Position = 0;
                return stream;
            }
    
            /// <summary>
            /// 将传入的数据量进行反序列化。
            /// </summary>
            /// <typeparam name="T">类的类型</typeparam>
            /// <param name="stream">要反序列化的流</param>
            /// <param name="bXmlOrBin">true=xml序列化,false=二进制序列化</param>
            /// <returns></returns>
            public T Deserialize<T>(Stream stream, bool bXmlOrBin = true)
            {
                T model = default(T);
                using (var newstream = stream)
                {
                    if (bXmlOrBin)
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(T));
                        //暂时没做什么处理,以后有日志文件,就直接添加进入
                        serializer.UnknownNode += new XmlNodeEventHandler(serializer_UnknownNode);
                        serializer.UnknownAttribute += new XmlAttributeEventHandler(serializer_UnknownAttribute);
                        model = (T)serializer.Deserialize(newstream);
                    }
                    else
                    {
                        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = null;
                        bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        model = (T)bf.Deserialize(newstream);
                    }
                }
                return model;
            }
    
            #region 反序列化中出错的问题
            private void serializer_UnknownNode(object sender, XmlNodeEventArgs e)
            {
                string aaaa = "Unknown Node:" + e.Name + "	" + e.Text;
                string bb = string.Empty;
                //Console.WriteLine("Unknown Node:" + e.Name + "	" + e.Text);
            }
    
            private void serializer_UnknownAttribute(object sender, XmlAttributeEventArgs e)
            {
                //System.Xml.XmlAttribute attr = e.Attr;
                //Console.WriteLine("Unknown attribute " +
                //attr.Name + "='" + attr.Value + "'");
                System.Xml.XmlAttribute attr = e.Attr;
                string aaaa = "Unknown attribute " + attr.Name + "='" + attr.Value + "'";
                string bb = string.Empty;
            }
            #endregion
    
            #endregion

    XML解析序列化2

    /// <summary>
        /// 实体转Xml,Xml转实体类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public class XmlHelper<T> where T : new()
        {
            #region 实体类转成Xml
            /// <summary>
            /// 对象实例转成xml
            /// </summary>
            /// <param name="item">对象实例</param>
            /// <returns></returns>
            public static string EntityToXml(T item)
            {
                IList<T> items = new List<T>();
                items.Add(item);
                return EntityToXml(items);
            }
    
            /// <summary>
            /// 对象实例集转成xml
            /// </summary>
            /// <param name="items">对象实例集</param>
            /// <returns></returns>
            public static string EntityToXml(IList<T> items)
            {
                //创建XmlDocument文档
                XmlDocument doc = new XmlDocument();
                //创建根元素
                XmlElement root = doc.CreateElement("s");//typeof(T).Name + 
                //添加根元素的子元素集
                foreach (T item in items)
                {
                    EntityToXml(doc, root, item);
                }
                //向XmlDocument文档添加根元素
                doc.AppendChild(root);
    
                return doc.InnerXml;
            }
    
            private static void EntityToXml(XmlDocument doc, XmlElement root, T item)
            {
                //创建元素
                XmlElement xmlItem = doc.CreateElement("t");//typeof(T).Name
                //对象的属性集
    
                System.Reflection.PropertyInfo[] propertyInfo =
                typeof(T).GetProperties(System.Reflection.BindingFlags.Public |
                System.Reflection.BindingFlags.Instance);
    
    
    
                foreach (System.Reflection.PropertyInfo pinfo in propertyInfo)
                {
                    if (pinfo != null)
                    {
                        //对象属性名称
                        string name = pinfo.Name;
                        //对象属性值
                        string value = String.Empty;
    
                        if (pinfo.GetValue(item, null) != null)
                            value = pinfo.GetValue(item, null).ToString();//获取对象属性值
                        //设置元素的属性值
                        xmlItem.SetAttribute(name, value);
                    }
                }
                //向根添加子元素
                root.AppendChild(xmlItem);
            }
    
    
            #endregion
    
            #region Xml转成实体类
    
            /// <summary>
            /// Xml转成对象实例
            /// </summary>
            /// <param name="xml">xml</param>
            /// <returns></returns>
            public static T XmlToEntity(string xml)
            {
                IList<T> items = XmlToEntityList(xml);
                if (items != null && items.Count > 0)
                    return items[0];
                else return default(T);
            }
    
            /// <summary>
            /// Xml转成对象实例集
            /// </summary>
            /// <param name="xml">xml</param>
            /// <returns></returns>
            public static IList<T> XmlToEntityList(string xml)
            {
                XmlDocument doc = new XmlDocument();
                try
                {
                    doc.Load(xml);//LoadXML
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                if (doc.ChildNodes.Count <= 1)
                    return null;
                //if (doc.ChildNodes[0].Name.ToLower() != typeof(T).Name.ToLower() + "s")
                //    return null;
    
                XmlNode node = doc.ChildNodes[1];
    
                IList<T> items = new List<T>();
    
                foreach (XmlNode child in node.ChildNodes)
                {
                    if (child.Name.ToLower() == typeof(T).Name.ToLower())
                        items.Add(XmlNodeToEntity(child));
                }
    
                return items;
            }
    
            private static T XmlNodeToEntity(XmlNode node)
            {
                T item = new T();
    
                if (node.NodeType == XmlNodeType.Element)
                {
                    //XmlElement element = (XmlElement)node;
    
                    System.Reflection.PropertyInfo[] propertyInfo =
                typeof(T).GetProperties(System.Reflection.BindingFlags.Public |
                System.Reflection.BindingFlags.Instance);
    
                    foreach (XmlNode attr in node.ChildNodes)//XmlAttribute
                    {
                        string attrName = attr.Name.ToLower();
                        string attrValue = attr.InnerXml.ToString();
                        foreach (System.Reflection.PropertyInfo pinfo in propertyInfo)
                        {
                            if (pinfo != null)
                            {
                                string name = pinfo.Name.ToLower();
                                Type dbType = pinfo.PropertyType;
                                if (name == attrName)
                                {
                                    if (String.IsNullOrEmpty(attrValue))
                                        continue;
                                    switch (dbType.ToString())
                                    {
                                        case "System.Int32":
                                            pinfo.SetValue(item, Convert.ToInt32(attrValue), null);
                                            break;
                                        case "System.Boolean":
                                            pinfo.SetValue(item, Convert.ToBoolean(attrValue), null);
                                            break;
                                        case "System.DateTime":
                                            pinfo.SetValue(item, Convert.ToDateTime(attrValue), null);
                                            break;
                                        case "System.Decimal":
                                            pinfo.SetValue(item, Convert.ToDecimal(attrValue), null);
                                            break;
                                        case "System.Double":
                                            pinfo.SetValue(item, Convert.ToDouble(attrValue), null);
                                            break;
                                        default:
                                            pinfo.SetValue(item, attrValue, null);
                                            break;
                                    }
                                    continue;
                                }
                            }
                        }
                    }
                }
                return item;
            }
    
            #endregion
        }
    
    //IList<ds> listDS = new List<MainWeb.ds>();
    //listDS = XmlHelper<ds>.XmlToEntityList("D:\DownLoad\数据\2017-03.xml");
    /// <summary>
            /// 根据节点读取xml指定节点内容
            /// </summary>
            /// <param name="spath">路径</param>
            /// <param name="nodeName">节点名字</param>
            /// <returns></returns>
            public static string getXMLNodeText(string spath, string nodeName)
            {
                try
                {
                    string uri = System.Web.HttpContext.Current.Server.MapPath("~/" + spath);
                    XmlDocument doc = new XmlDocument();
                    doc.Load(uri);
                    XmlElement eml = doc.SelectSingleNode("/" + nodeName) as XmlElement;
                    string result = eml.InnerText;
                    return result;
                }
                catch
                {
                    return "";
                }
            }
    
    
    
    string strNode = getXMLNodeText("Web层文件路径", "documentXML/ParentNode/ChildNode");

    根据IP获取城市--有道接口

     string Uri = "http://www.yodao.com/smartresult-xml/search.s?type=ip&q=" + IP;
    
                //获取省份名称
                string CtryDisc = MyRegex.HttpWeb.getHtmlByUri(Uri, Encoding.GetEncoding("GB2312"));
                using (XmlReader read = XmlReader.Create(CtryDisc))//获取返回的xml格式文件内容
                {
                    while (read.Read())
                    {
                        switch (read.NodeType)
                        {
                            case XmlNodeType.Text://取xml格式文件当中的文本内容
                                if (string.Format("{0}", read.Value).ToString().Trim() != IP)//youdao返回的xml格式文件内容一个是IP,另一个是IP地址
                                {
                                    CtryDisc = string.Format("{0}", read.Value).ToString().Trim();//赋值
                                }
                                break;
                            //other
                        }
                    }
                }

    config.xml

    #region XML控制
            public XmlDocument xml = null;
            public string xmlpath = string.Empty;
            /// <summary>
            /// 以XML格式进行存储
            /// </summary>
            public bool Save(string id, string data, string nodes, string key, string value, bool isMsg)
            {
                if (!IsXml(isMsg)) return false;
                foreach (XmlNode xl in xml.SelectNodes(nodes))
                {
                    if (xl.Attributes[key].Value == id)
                    {
                        xl.Attributes[value].Value = data;
                        break;
                    }
                }
                xml.Save(xmlpath);
                return true;
            }
    
            /// <summary>
            /// 获取数据
            /// </summary>
            public string GetData(string id, string nodes, string key, string value, bool isMsg)
            {
                if (!IsXml(isMsg)) return "";
                foreach (XmlNode xl in xml.SelectNodes(nodes))
                {
                    if (xl.Attributes[key].Value == id)
                        return xl.Attributes[value].Value;
                }
                return "";
            }
    
            /// <summary>
            /// 判断XML文件是否存在
            /// </summary>
            /// <returns></returns>
            public bool IsXml(bool isMsg)
            {
                FileInfo file = new FileInfo(xmlpath);
                if (!file.Exists)
                {
                    if (isMsg)
                        MessageBox.Show(string.Format("无法找到数据配置文件:{0}
    请联系管理员!", file.Name));
                    return false;
                }
                file.IsReadOnly = false;
                xml = new XmlDocument();
                xml.Load(xmlpath);
                return true;
            }
            #endregion
    
    xmlpath = string.Format(@"{0}config.xml", AppDomain.CurrentDomain.BaseDirectory);
                    if (!File.Exists(xmlpath))
                    {
                        MessageBox.Show("找不到config.xml配置文件请联系管理员!");
                        return;
                    }
    
    
      /*             
                    string _appStrPath = "/configuration/appSettings/add";
                    string _depart = GetData("depart", _appStrPath, "key", "value", false);
    */
                

    /// <summary>    /// 实体转Xml,Xml转实体类    /// </summary>    /// <typeparam name="T"></typeparam>    public class XmlHelper<T> where T : new()    {        #region 实体类转成Xml        /// <summary>        /// 对象实例转成xml        /// </summary>        /// <param name="item">对象实例</param>        /// <returns></returns>        public static string EntityToXml(T item)        {            IList<T> items = new List<T>();            items.Add(item);            return EntityToXml(items);        }
            /// <summary>        /// 对象实例集转成xml        /// </summary>        /// <param name="items">对象实例集</param>        /// <returns></returns>        public static string EntityToXml(IList<T> items)        {            //创建XmlDocument文档            XmlDocument doc = new XmlDocument();            //创建根元素            XmlElement root = doc.CreateElement("s");//typeof(T).Name +             //添加根元素的子元素集            foreach (T item in items)            {                EntityToXml(doc, root, item);            }            //向XmlDocument文档添加根元素            doc.AppendChild(root);
                return doc.InnerXml;        }
            private static void EntityToXml(XmlDocument doc, XmlElement root, T item)        {            //创建元素            XmlElement xmlItem = doc.CreateElement("t");//typeof(T).Name            //对象的属性集
                System.Reflection.PropertyInfo[] propertyInfo =            typeof(T).GetProperties(System.Reflection.BindingFlags.Public |            System.Reflection.BindingFlags.Instance);


                foreach (System.Reflection.PropertyInfo pinfo in propertyInfo)            {                if (pinfo != null)                {                    //对象属性名称                    string name = pinfo.Name;                    //对象属性值                    string value = String.Empty;
                        if (pinfo.GetValue(item, null) != null)                        value = pinfo.GetValue(item, null).ToString();//获取对象属性值                    //设置元素的属性值                    xmlItem.SetAttribute(name, value);                }            }            //向根添加子元素            root.AppendChild(xmlItem);        }

            #endregion
            #region Xml转成实体类
            /// <summary>        /// Xml转成对象实例        /// </summary>        /// <param name="xml">xml</param>        /// <returns></returns>        public static T XmlToEntity(string xml)        {            IList<T> items = XmlToEntityList(xml);            if (items != null && items.Count > 0)                return items[0];            else return default(T);        }
            /// <summary>        /// Xml转成对象实例集        /// </summary>        /// <param name="xml">xml</param>        /// <returns></returns>        public static IList<T> XmlToEntityList(string xml)        {            XmlDocument doc = new XmlDocument();            try            {                doc.Load(xml);//LoadXML            }            catch (Exception ex)            {                throw ex;            }            if (doc.ChildNodes.Count <= 1)                return null;            //if (doc.ChildNodes[0].Name.ToLower() != typeof(T).Name.ToLower() + "s")            //    return null;
                XmlNode node = doc.ChildNodes[1];
                IList<T> items = new List<T>();
                foreach (XmlNode child in node.ChildNodes)            {                if (child.Name.ToLower() == typeof(T).Name.ToLower())                    items.Add(XmlNodeToEntity(child));            }
                return items;        }
            private static T XmlNodeToEntity(XmlNode node)        {            T item = new T();
                if (node.NodeType == XmlNodeType.Element)            {                //XmlElement element = (XmlElement)node;
                    System.Reflection.PropertyInfo[] propertyInfo =            typeof(T).GetProperties(System.Reflection.BindingFlags.Public |            System.Reflection.BindingFlags.Instance);
                    foreach (XmlNode attr in node.ChildNodes)//XmlAttribute                {                    string attrName = attr.Name.ToLower();                    string attrValue = attr.InnerXml.ToString();                    foreach (System.Reflection.PropertyInfo pinfo in propertyInfo)                    {                        if (pinfo != null)                        {                            string name = pinfo.Name.ToLower();                            Type dbType = pinfo.PropertyType;                            if (name == attrName)                            {                                if (String.IsNullOrEmpty(attrValue))                                    continue;                                switch (dbType.ToString())                                {                                    case "System.Int32":                                        pinfo.SetValue(item, Convert.ToInt32(attrValue), null);                                        break;                                    case "System.Boolean":                                        pinfo.SetValue(item, Convert.ToBoolean(attrValue), null);                                        break;                                    case "System.DateTime":                                        pinfo.SetValue(item, Convert.ToDateTime(attrValue), null);                                        break;                                    case "System.Decimal":                                        pinfo.SetValue(item, Convert.ToDecimal(attrValue), null);                                        break;                                    case "System.Double":                                        pinfo.SetValue(item, Convert.ToDouble(attrValue), null);                                        break;                                    default:                                        pinfo.SetValue(item, attrValue, null);                                        break;                                }                                continue;                            }                        }                    }                }            }            return item;        }
            #endregion    }

  • 相关阅读:
    JS和C#对Json的操作
    JS图形化插件利器组件系列 —— Gojs组件
    Android APK反编译 apktool使用教程
    UML系列图
    多线程学习 ---- 系列教程
    大型网站架构之系列
    经典算法题锦集
    基本算法系列15天速成
    居转户--相关信息
    使用C#创建Windows服务
  • 原文地址:https://www.cnblogs.com/elves/p/3610547.html
Copyright © 2020-2023  润新知