C++开发博客CSDN

将对象序列化

using System.IO;
using System.Xml;
using System.Xml.Serialization;      
 
        /// <summary>
        
/// 将对象转换为 XML 字符串        
        
/// </summary>
        
/// <param name="obj"></param>
        
/// <returns></returns>
        public static string ToXmlString(Model.Student obj)
        {
            
using (MemoryStream ms = new MemoryStream())
            {
                System.Type type 
= obj.GetType();
                XmlSerializer serializer 
= new XmlSerializer(type);
                
try
                {
                    serializer.Serialize(ms, obj);
                    ms.Close();
                    
return Encoding.UTF8.GetString(ms.ToArray());
                }
                
catch (Exception ex)
                {
                    Debug.Print(ex.ToString());
                    
return string.Empty;
                }
            }
        }


        
/// <summary>
        
/// 将对象转换为 XML 文件        
        
/// </summary>
        
/// <param name="obj"></param>
        
/// <returns></returns>
        public static void ToXmlFile(Model.Student obj)
        {
            
using (FileStream fs = new FileStream(@"D:\xsdj.xml", FileMode.Create))
            {
                System.Type type 
= obj.GetType();
                XmlSerializer serializer 
= new XmlSerializer(type);
                
try
                {
                    serializer.Serialize(fs, obj);
                    fs.Close();
                }
                
catch (Exception ex)
                {
                    Debug.Print(ex.ToString());
                }
            }
        }
posted @ 2011-09-15 09:03  纳凉亭子  阅读(148)  评论(0编辑  收藏  举报