16_通过XMLSeralizer序列化xml文件
时间: 2023-07-16 14:17:01 浏览: 46
XMLSerializer是.NET中的一个类,用于将对象序列化为XML格式或将XML文档反序列化为对象。以下是使用XMLSerializer序列化xml文件的步骤:
1. 创建一个要序列化的对象,并对其进行赋值。
2. 创建一个XMLSerializer对象。
3. 使用XMLSerializer对象的Serialize方法将对象序列化为XML格式的字符串。
4. 将XML格式的字符串写入XML文件中。
以下是一个示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//创建一个要序列化的对象
List<Student> students = new List<Student>()
{
new Student{Id=1,Name="Tom",Age=18},
new Student{Id=2,Name="Jerry",Age=20},
new Student{Id=3,Name="Lucy",Age=19},
};
//创建XMLSerializer对象
XmlSerializer serializer = new XmlSerializer(typeof(List<Student>));
//使用XMLSerializer对象的Serialize方法将对象序列化为XML格式的字符串
StringWriter writer = new StringWriter();
serializer.Serialize(writer, students);
string xmlString = writer.ToString();
//将XML格式的字符串写入XML文件中
using (StreamWriter sw = new StreamWriter("students.xml"))
{
sw.Write(xmlString);
}
Console.WriteLine("序列化完成!");
Console.ReadKey();
}
}
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
}
```
运行上述代码后,将在项目目录下生成一个名为“students.xml”的XML文件,其中包含了序列化的数据。