C#—XML格式序列化和反序列化
在C#中,可以使用System.Xml.Serialization命名空间下的XmlSerializer类来实现XML的序列化。
首先,定义一个可序列化的对象模型:
using System;
using System.Xml.Serialization;[XmlRoot("Person")]
public class Person
{[XmlElement("Name")]public string Name { get; set; }[XmlElement("Age")]public int Age { get; set; }
}
序列化
using System.IO;
using System.Xml.Serialization;public static string SerializeObject(Person obj)
{XmlSerializer serializer = new XmlSerializer(typeof(Person));using (StringWriter textWriter = new StringWriter()){serializer.Serialize(textWriter, obj);return textWriter.ToString();}
}
反序列化
using System.IO;
using System.Xml.Serialization;public static Person DeserializeObject(string xml)
{XmlSerializer serializer = new XmlSerializer(typeof(Person));using (StringReader textReader = new StringReader(xml)){return (Person)serializer.Deserialize(textReader);}
}
使用方法
Person person = new Person { Name = "John Doe", Age = 30 };
string xml = SerializeObject(person);
Console.WriteLine(xml);Person deserializedPerson = DeserializeObject(xml);
Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
这个例子中,我们定义了一个Person类,并用XmlRoot和XmlElement属性标记了类和属性,以指导XML序列化器如何序列化对象的属性。然后,我们创建了两个方法,SerializeObject用于将Person对象序列化为XML字符串,DeserializeObject用于将XML字符串反序列化为Person对象。最后,我们创建了一个Person对象,将其序列化,然后反序列化,并打印出结果。