• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
一个具有上进心的码农
因为一篇文章中有很多是从很多篇文章中摘取的,请恕我没有一一说明摘取出处,如果没有说明,则该文章默认是摘取,如有侵犯您的权益,请与我联系,将会马上删除。
博客园    首页    新随笔    联系   管理    订阅  订阅

XML序列化

今天写文件时,突然忘了这么一个重要的方法..  记下来吧/

 

 

代码
// 调用
DeSerializeDocument("d:\\books.xml");

  
public MyRootClass DeSerializeDocument(string filename)  
        {

            XmlSerializer s 
= new XmlSerializer(typeof(MyRootClass));
             TextReader myRead 
= new StreamReader(filename);
           MyRootClass obj 
=  s.Deserialize(myRead) as MyRootClass;
           
return obj;
        }

 
public void SerializeDocument(string filename)   
        {            
// Creates a new XmlSerializer.          

            XmlSerializer s 
=      new XmlSerializer(typeof(MyRootClass));       
            
// Writing the file requires a StreamWriter.          
           
            TextWriter myWriter 
= new StreamWriter(filename);          
            
// Creates an instance of the class to serialize.         
            
            MyRootClass myRootClass 
= new MyRootClass();                   
            
//create items        
            Item item1 = new Item();           
            
// Sets the objects' properties.          
            item1.ItemName = "Widget1";        
           
            item1.ItemCode 
= "w1";      
            item1.ItemPrice 
= 231;    
            item1.ItemQuantity 
= 3;          


            Item item2 
= new Item();        
            item2.ItemName 
= "Widget2";            
            item2.ItemCode 
= "w2";        
            item2.ItemPrice 
= 800;       
            item2.ItemQuantity 
= 2;             // Sets the class's Items property to the list.    
            myRootClass.Items.Add(item1);          
            myRootClass.Items.Add(item2);             
/* Serializes the class, writes it to 

disk, and closes                the TextWriter. 
*/          
            s.Serialize(myWriter, myRootClass);           
            myWriter.Close();       
        
        }
    }

    [Serializable]
    
public class MyRootClass
    {

        
public MyRootClass()
        {
            items 
=new List<Item>();
        }

        
private List<Item> items;
        
        
public List<Item> Items
        {
            
get { return items; }

            
set { items = value; }
        }
    }


    
public class Item
    {
        
public string ItemName;

        
public string ItemCode;

        
public decimal ItemPrice; 
        
        
public int ItemQuantity;
    }

 

 

posted @ 2010-03-08 17:36  不若相忘于江湖  阅读(168)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3