xml 序列化实例
时间: 2023-08-16 20:05:07 浏览: 109
下面是一个简单的 XML 序列化实例,假设我们有一个名为 Person 的类:
```csharp
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
```
现在我们将创建一个 Person 实例,将其序列化为 XML 字符串,然后将其反序列化为新的 Person 实例。以下是代码示例:
```csharp
using System;
using System.IO;
using System.Xml.Serialization;
class Program
{
static void Main(string[] args)
{
// 创建一个 Person 实例
var person = new Person { Name = "John Doe", Age = 30 };
// 创建一个 XmlSerializer 对象
var serializer = new XmlSerializer(typeof(Person));
// 将 Person 实例序列化为 XML 字符串
var stringWriter = new StringWriter();
serializer.Serialize(stringWriter, person);
var xml = stringWriter.ToString();
Console.WriteLine("Serialized XML:");
Console.WriteLine(xml);
Console.WriteLine();
// 将 XML 字符串反序列化为新的 Person 实例
var stringReader = new StringReader(xml);
var newPerson = (Person)serializer.Deserialize(stringReader);
Console.WriteLine("Deserialized Person:");
Console.WriteLine($"Name: {newPerson.Name}");
Console.WriteLine($"Age: {newPerson.Age}");
}
}
```
输出:
```
Serialized XML:
<?xml version="1.0" encoding="utf-16"?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>John Doe</Name>
<Age>30</Age>
</Person>
Deserialized Person:
Name: John Doe
Age: 30
```
阅读全文