C# 的 XmlSerializer 类用于将对象序列化为 XML 字符串,或将 XML 字符串反序列化为对象。以下是如何使用 XmlSerializer 的基本步骤:
Person
的类:public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
XmlSerializer serializer = new XmlSerializer(typeof(Person));
Serialize
方法将对象序列化为 XML 字符串:Person person = new Person { FirstName = "John", LastName = "Doe", Age = 30 };
string xmlString;
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, person);
xmlString = writer.ToString();
}
Console.WriteLine(xmlString);
这将输出以下 XML 字符串:
<Person>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Age>30</Age>
</Person>
Deserialize
方法将 XML 字符串反序列化为对象:string xmlString = "<Person><FirstName>Jane</FirstName><LastName>Doe</LastName><Age>28</Age></Person>";
using (StringReader reader = new StringReader(xmlString))
{
Person person = (Person)serializer.Deserialize(reader);
Console.WriteLine($"FirstName: {person.FirstName}, LastName: {person.LastName}, Age: {person.Age}");
}
这将输出:
FirstName: Jane, LastName: Doe, Age: 28
注意:在使用 XmlSerializer 时,需要确保类的属性具有公共 getter 和 setter 方法。如果某个类需要特殊处理,可以实现 IXmlSerializable
接口并重写 WriteXml
和 ReadXml
方法。