帮我写一个C#类,实现将复杂的Person类序列化成xml格式,并且能够反序列化为类对象
时间: 2024-09-28 08:13:28 浏览: 31
C#实现对象XML序列化的方法
在C#中,我们可以创建一个`Person`类,并使用`System.Xml.Serialization`命名空间下的特性来实现XML序列化和反序列化。这里是一个简单的例子:
首先,我们定义`Person`类:
```csharp
using System;
using System.Xml.Serialization;
[XmlRoot("Person")]
public class Person
{
[XmlElement("FirstName")]
public string FirstName { get; set; }
[XmlElement("LastName")]
public string LastName { get; set; }
[XmlElement("Age")]
public int Age { get; set; }
[XmlElement("Email")]
public string Email { get; set; }
[XmlAttribute("Id")] // 如果想作为属性而不是元素,则加上[XmlAttribute]
public Guid Id { get; set; }
public Person(string firstName, string lastName, int age, string email, Guid id)
{
FirstName = firstName;
LastName = lastName;
Age = age;
Email = email;
Id = id;
}
}
```
然后,我们将一个`Person`对象序列化为XML:
```csharp
static void SerializePerson(Person person)
{
var serializer = new XmlSerializer(typeof(Person));
using (var writer = new System.IO.StringWriter())
{
serializer.Serialize(writer, person);
Console.WriteLine(writer.ToString());
}
}
// 使用示例
var p = new Person("John", "Doe", 30, "john.doe@example.com", Guid.NewGuid());
SerializePerson(p);
```
接下来,我们可以从XML字符串反序列化回`Person`对象:
```csharp
static Person DeserializePerson(string xml)
{
var serializer = new XmlSerializer(typeof(Person));
using (var reader = new StringReader(xml))
{
return (Person)serializer.Deserialize(reader);
}
}
// 示例
string xmlString = ... // 从文件或其他源获取XML字符串
var deserializedPerson = DeserializePerson(xmlString);
```
阅读全文