csharp 此类演示了将对象序列化和反序列化为xml字符串的方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 此类演示了将对象序列化和反序列化为xml字符串的方法相关的知识,希望对你有一定的参考价值。

class XmlSerializationProgram
{
	static void Main(string[] args)
	{
		var person = new Person
		{
			firstName = "John",
			lastName = "Doe",
			dateOfBirth = new MyDate
			{
				year = 1901,
				month = 4,
				day = 30
			}
		};

		Method1(person);
		Method2(person);

		Console.WriteLine("\r\nFinished.");
		Console.ReadLine();
	}

	#region Method1
	private static void Method1(Person person)
	{
		var ser = new System.Xml.Serialization.XmlSerializer(typeof(Person));

		var writer = new StringWriter();
		ser.Serialize(writer, person);

		var xml = writer.ToString();

		var reader = new StringReader(xml);
		var anotherObject = ser.Deserialize(reader) as Person;
	}
	#endregion

	#region Method2
	private static void Method2(Person person)
	{
		var ser = new System.Runtime.Serialization.DataContractSerializer(typeof(Person));
		var output = "";

		using (var ms = new MemoryStream())
		{
			ser.WriteObject(ms, person);
			output = Encoding.Default.GetString(ms.ToArray());
		}

		using (var ms = new MemoryStream(Encoding.Default.GetBytes(output)))
		{
			var anotherObject = ser.ReadObject(ms) as Person;
		}
	}
	#endregion

	public class MyDate
	{
		public int year;
		public int month;
		public int day;
	}

	public class Person
	{
		public string firstName;
		public string lastName;
		public MyDate dateOfBirth;
	}
}

以上是关于csharp 此类演示了将对象序列化和反序列化为xml字符串的方法的主要内容,如果未能解决你的问题,请参考以下文章

将 Objective-C 对象序列化和反序列化为 JSON

csharp 使用Newtonsoft JSON.NET将任何对象序列化/反序列化为JSON

csharp 将C#类对象写入/序列化为JSON对象

对象序列化和反序列化

序列化和反序列化

xml对象的序列化和反序列化