c sharp如何使用xmlserializer进行序列化与反序列化
时间: 2024-05-15 17:19:10 浏览: 73
xml序列化与反序列化
可以使用以下代码进行C#中的XML序列化和反序列化:
序列化:
```csharp
using System.Xml.Serialization;
using System.IO;
//将对象序列化为XML字符串
public static string SerializeObjectToXml<T>(T obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj);
return writer.ToString();
}
}
```
反序列化:
```csharp
using System.Xml.Serialization;
using System.IO;
//将XML字符串反序列化为对象
public static T DeserializeObjectFromXml<T>(string xml)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(xml))
{
return (T)serializer.Deserialize(reader);
}
}
```
你可以通过调用SerializeObjectToXml方法将对象序列化为XML字符串,通过调用DeserializeObjectFromXml方法将XML字符串反序列化为对象。
阅读全文