Use XML Serialization with Custom Objects

本文介绍了一个使用C#实现的XML序列化与反序列化示例,包括如何将自定义类实例写入XML文件及从XML文件中读取数据。示例展示了如何配置属性以指定XML元素名称、数据类型等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Use XML Serialization with Custom Objects

 

using  System;
using  System.Xml;
using  System.Xml.Serialization;
using  System.IO;

public class  SerializeXml  {
     private static  void  Main () {
         CarList catalog =  new  CarList ( "New List" , DateTime.Now.AddYears ( 1 )) ;
         Car []  cars =  new  Car [ 2 ] ;
         cars [ 0 new  Car ( "Car 1" 12342.99 m ) ;
         cars [ 1 new  Car ( "Car 2" 21234123.9 m ) ;
         catalog.Cars = cars;

         XmlSerializer serializer =  new  XmlSerializer ( typeof ( CarList )) ;
         FileStream fs =  new  FileStream ( "CarList.xml" , FileMode.Create ) ;
         serializer.Serialize ( fs, catalog ) ;
         fs.Close () ;

         catalog =  null ;

         // Deserialize the order from the file.
         fs =  new  FileStream ( "CarList.xml" , FileMode.Open ) ;
         catalog =  ( CarList ) serializer.Deserialize ( fs ) ;

         // Serialize the order to the Console window.
         serializer.Serialize ( Console.Out, catalog ) ;
     }
}


[ XmlRoot ( "carList" )]
public class  CarList  {

     [ XmlElement ( "catalogName" )]
     public  string ListName;
    
     // Use the date data type (and ignore the time portion in the serialized XML).
     [ XmlElement ( ElementName= "expiryDate" , DataType= "date" )]
     public  DateTime ExpiryDate;
    
     [ XmlArray ( "cars" )]
     [ XmlArrayItem ( "car" )]
     public  Car []  Cars;

     public  CarList () {
     }

     public  CarList ( string catalogName, DateTime expiryDate ) {
         this .ListName = catalogName;
         this .ExpiryDate = expiryDate;
     }
}

public class  Car  {

     [ XmlElement ( "carName" )]
     public  string CarName;
    
     [ XmlElement ( "carPrice" )]
     public  decimal CarPrice;
    
     [ XmlElement ( "inStock" )]
     public  bool InStock;
    
     [ XmlAttributeAttribute ( AttributeName= "id" , DataType= "integer" )]
     public  string Id;

     public  Car () {
     }
     public  Car ( string carName, decimal carPrice ) {
         this .CarName = carName;
         this .CarPrice = carPrice;
     }
}
           
         
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值