欢迎光临

木子屋

标题: C# XML序列化/反序列化类DataContractSerializer使用示例

作者: dnawo

日期: 2013-05-04 11:49 AM

分类: Win编程

内容: 复制内容到剪贴板 程序代码using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//序列化
Person person = new Person() { Name = "dnawo", Age = 100 };
string xml = Serialize(person);
Console.WriteLine(xml);
//反序列化
person = Deserialize<Person>(xml);
Console.WriteLine(person.Name);
Console.ReadKey();
}
/// <summary>
/// 序列化
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public static string Serialize(object o)
{
return Serialize(o, new UTF8Encoding(false));
}
/// <summary>
/// 序列化
/// </summary>
/// <param name="o"></param>
/// <param name="encode"></param>
/// <returns></returns>
public static string Serialize(object o, Encoding encode)
{
string result = string.Empty;
using (MemoryStream output = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(o.GetType());
serializer.WriteObject(output, o);
result = encode.GetString(output.ToArray());
}
return result;
}
/// <summary>
/// 反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="str"></param>
/// <returns></returns>
public static T Deserialize<T>(string str) where T : class
{
return Deserialize<T>(str, new UTF8Encoding(false));
}
/// <summary>
/// 反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="str"></param>
/// <param name="encode"></param>
/// <returns></returns>
public static T Deserialize<T>(string str, Encoding encode) where T : class
{
T result = null;
using (MemoryStream input = new MemoryStream(encode.GetBytes(str)))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
result = serializer.ReadObject(input) as T;
}
return result;
}
}
/// <summary>
/// 测试类
/// </summary>
[DataContract(Name="per")]
public class Person
{
[DataMember(Name="na")]
public string Name { get; set; }
[DataMember(Name="ag")]
public int Age { get; set; }
}
}
运行结果：
引用内容<per xmlns="http://schemas.datacontract.org/2004/07/ConsoleApplication1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><ag>100</ag><na>dnawo</na></per>
dnawo

+ 查看当前日志评论 (0)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 1.758 ms

返回

标题: C# XML序列化/反序列化类DataContractSerializer使用示例

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 1.758 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 1.789 ms

返回