本文描述如何使用CLR中的StringWriter,XmlSerializer将对象, 对象集合序列化为Xml格式的字符串, 同时描述如何进行反序列化.

C#版本: C# 3.0
开发环境: VS 2008

主要方法:

对象,对象集合的简单Xml序列化与反序列化using System;
对象,对象集合的简单Xml序列化与反序列化
using System.Collections.Generic;
对象,对象集合的简单Xml序列化与反序列化
using System.Linq;
对象,对象集合的简单Xml序列化与反序列化
using System.Text;
对象,对象集合的简单Xml序列化与反序列化
using System.IO;
对象,对象集合的简单Xml序列化与反序列化
using System.Xml;
对象,对象集合的简单Xml序列化与反序列化
using System.Xml.Serialization;
对象,对象集合的简单Xml序列化与反序列化
对象,对象集合的简单Xml序列化与反序列化
namespace ConsoleApplication2
}


定义一个用于测试的实体类: UserInfo

对象,对象集合的简单Xml序列化与反序列化using System;
对象,对象集合的简单Xml序列化与反序列化
using System.Collections.Generic;
对象,对象集合的简单Xml序列化与反序列化
using System.Linq;
对象,对象集合的简单Xml序列化与反序列化
using System.Text;
对象,对象集合的简单Xml序列化与反序列化
using System.Xml.Serialization;
对象,对象集合的简单Xml序列化与反序列化
对象,对象集合的简单Xml序列化与反序列化
namespace ConsoleApplication2
}

编写测试子程序:

对象,对象集合的简单Xml序列化与反序列化using System;
对象,对象集合的简单Xml序列化与反序列化
using System.Collections.Generic;
对象,对象集合的简单Xml序列化与反序列化
using System.Linq;
对象,对象集合的简单Xml序列化与反序列化
using System.Text;
对象,对象集合的简单Xml序列化与反序列化
对象,对象集合的简单Xml序列化与反序列化
namespace ConsoleApplication2
}

输出结果为:

<?xml version="1.0" encoding="utf-16"?>
<UserInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http:
//www.w3.org/2001/XMLSchema">
  <userId>1</userId>
  <userName>Guozhijian</userName>
</UserInfo>

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfUserInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd
="http://www.w3.org/2001/XMLSchema">
  <UserInfo>
    <userId>1</userId>
    <userName>Guozhijian</userName>
  </UserInfo>
  <UserInfo>
    <userId>2</userId>
    <userName>Zhenglanzhen</userName>
  </UserInfo>
</ArrayOfUserInfo>

1, Guozhijian

1, Guozhijian
2, Zhenglanzhen

相关文章: