在C#中,可以使用多種方法進行XML序列化
XmlSerializer
類:這是最常用的方法,通過創建XmlSerializer
對象并調用其Serialize
和Deserialize
方法來實現對象的序列化和反序列化。using System.IO;
using System.Xml.Serialization;
public class Program
{
public static void Main()
{
// 創建一個要序列化的對象
Person person = new Person { Name = "John", Age = 30 };
// 創建一個XmlSerializer對象
XmlSerializer serializer = new XmlSerializer(typeof(Person));
// 將對象序列化為XML字符串
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, person);
string xmlString = writer.ToString();
Console.WriteLine("Serialized XML: " + xmlString);
}
// 從XML字符串反序列化為對象
using (StringReader reader = new StringReader(xmlString))
{
Person deserializedPerson = (Person)serializer.Deserialize(reader);
Console.WriteLine("Deserialized object: Name = {0}, Age = {1}", deserializedPerson.Name, deserializedPerson.Age);
}
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
DataContractSerializer
類:這是另一種用于序列化和反序列化對象的方法,主要用于WCF服務。與XmlSerializer
相比,DataContractSerializer
提供了更好的性能和更簡潔的XML輸出。using System.IO;
using System.Runtime.Serialization;
public class Program
{
public static void Main()
{
// 創建一個要序列化的對象
Person person = new Person { Name = "John", Age = 30 };
// 創建一個DataContractSerializer對象
DataContractSerializer serializer = new DataContractSerializer(typeof(Person));
// 將對象序列化為XML字符串
using (MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, person);
string xmlString = Encoding.UTF8.GetString(stream.ToArray());
Console.WriteLine("Serialized XML: " + xmlString);
}
// 從XML字符串反序列化為對象
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
{
Person deserializedPerson = (Person)serializer.ReadObject(stream);
Console.WriteLine("Deserialized object: Name = {0}, Age = {1}", deserializedPerson.Name, deserializedPerson.Age);
}
}
}
[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
}
XmlDocument
或XDocument
類:這些類提供了對XML文檔的直接操作,允許您手動構建和解析XML結構。這種方法比使用序列化器更復雜,但提供了更大的控制和靈活性。using System.Xml;
using System.Xml.Linq;
public class Program
{
public static void Main()
{
// 創建一個要序列化的對象
Person person = new Person { Name = "John", Age = 30 };
// 使用XDocument手動構建XML
XDocument doc = new XDocument(
new XElement("Person",
new XElement("Name", person.Name),
new XElement("Age", person.Age)
)
);
// 將XDocument轉換為字符串
string xmlString = doc.ToString();
Console.WriteLine("Serialized XML: " + xmlString);
// 從XML字符串反序列化為對象
XDocument deserializedDoc = XDocument.Parse(xmlString);
Person deserializedPerson = new Person
{
Name = deserializedDoc.Root.Element("Name").Value,
Age = int.Parse(deserializedDoc.Root.Element("Age").Value)
};
Console.WriteLine("Deserialized object: Name = {0}, Age = {1}", deserializedPerson.Name, deserializedPerson.Age);
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
這些方法都可以用于在C#中進行XML序列化。選擇哪種方法取決于您的需求和項目的特定要求。