使用XML 序列化和反序列化类对象的方法

本文介绍如何使用.NET Framework中的XML序列化方法将自定义对象转换为XML字符串,并将其反序列化回对象状态。通过示例展示了序列化与反序列化的实现过程。

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

.NET  Framework提供了多种序列化对象的方法,二进制,XML,  SOAP,而在系统中应用往往使用对象序列化来暂存或缓存对象状态。

第一步,序列化对象到字串

        public static string GetObjectXML(object e)
        
{
            XmlSerializer serilizer 
= new XmlSerializer(typeof(Employee));

            System.Text.StringBuilder sbXML 
= new StringBuilder();

            System.IO.StringWriter writer 
= new System.IO.StringWriter(sbXML);

            serilizer.Serialize(writer, e);

            writer.Close();

            
return sbXML.ToString();
        }

 

第二步,将字串反序列化为对象
        public static Employee GetObjectFromXML(string xml)
        
{
            XmlSerializer serializer 
= new XmlSerializer(typeof(Employee));

            System.IO.StringReader reader 
= new System.IO.StringReader(xml);

            Employee emp 
= (Employee)serializer.Deserialize(reader);

            
return emp;
        }


Employee是自定义对象,XML 序列化只能序列化public属性,无值的属性不生成XML Tag.

调用示例:
        static void Main(string[] args)
        
{
            Employee emp 
= new Employee();
            emp.FirstName 
= "Johnson";
            emp.LastName 
= "Yang";
            emp.Id 
= 1;

            Console.WriteLine(
"{0}", GetObjectXML(emp));

            Console.WriteLine(
"First Name = {0}", GetObjectFromXML(GetObjectXML(emp)).FirstName);
        }



//Employee

    
public class Employee
    
{
        
member variables

        
public properties
    }




//输出结果

<?xml version="1.0" encoding="utf-16"?>
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http:
//www.w3.org/2001/XMLSchema">
  <Id>1</Id>
  <FirstName>Johnson</FirstName>
  <LastName>Yang</LastName>
  <BirthDay>2007-03-13T21:51:33.078125+08:00</BirthDay>
</Employee>
First Name = Johnson
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值