码迷,mamicode.com
首页 > Windows程序 > 详细

C#中xml操作

时间:2015-06-03 11:15:11      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

序列化成一个字符串:

public static string XMLSerialize<T>(T entity)  
       {  
           StringBuilder buffer = new StringBuilder();  
             
           XmlSerializer serializer = new XmlSerializer(typeof(T));  
           using (TextWriter writer = new StringWriter(buffer))  
           {  
               serializer.Serialize(writer, entity);  
           }  
           
           return buffer.ToString();  
             
       } 

反序列化成对象:

    public static T DeXMLSerialize<T>(string xmlString)  
            {  
                T cloneObject = default(T);  
      
                StringBuilder buffer = new StringBuilder();  
                buffer.Append(xmlString);  
      
                XmlSerializer serializer = new XmlSerializer(typeof(T));  
      
                using (TextReader reader = new StringReader(buffer.ToString()))  
                {  
                    Object obj = serializer.Deserialize(reader);  
                    cloneObject = (T)obj;  
                }  
      
                return cloneObject;  
            }  

利用MemoryStream的形式:

 public static string XmlSerialize<T>(T obj)  
    {  
        string xmlString = string.Empty;  
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));  
        using (MemoryStream ms = new MemoryStream())  
        {  
            xmlSerializer.Serialize(ms, obj);  
            xmlString = Encoding.UTF8.GetString(ms.ToArray());  
        }  
        return xmlString;  
    }
  public static T XmlDeserialize<T>(string xmlString)  
    {  
        T t = default(T);  
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));  
        using (Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))  
        {  
            using (XmlReader xmlReader = XmlReader.Create(xmlStream))  
            {  
                Object obj = xmlSerializer.Deserialize(xmlReader);  
                t = (T)obj;  
            }  
        }  
        return t;  
    }  

生成文件:

string strFile = @"c:/zero.xml";
            using (FileStream fs = new FileStream(strFile, FileMode.Create))
            {
                XmlSerializer formatter = new XmlSerializer(typeof(T));
                formatter.Serialize(fs, entity);
            }
StringBuilder sb = new StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);

XmlSerializer formatter = new XmlSerializer(typeof(T));
formatter .Serialize(writer,entity );

 

C#中xml操作

标签:

原文地址:http://www.cnblogs.com/zxiong/p/4548371.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!