c#xml序列化规定encoding=utf-8
时间: 2023-11-22 15:58:22 浏览: 151
C# 生成xml文件,编码为utf-8方法
5星 · 资源好评率100%
在C#中进行XML序列化时,默认的编码方式是UTF-8。但是,我们也可以通过设置XmlWriterSettings.Encoding属性来指定其他的编码方式。下面是一个示例代码:
```csharp
using System;
using System.IO;
using System.Xml.Serialization;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Program
{
static void Main(string[] args)
{
Person person = new Person { Name = "Alice", Age = 20 };
XmlSerializer serializer = new XmlSerializer(typeof(Person));
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = System.Text.Encoding.UTF32; // 指定编码方式为UTF-32
using (XmlWriter writer = XmlWriter.Create("person.xml", settings))
{
serializer.Serialize(writer, person);
}
}
}
```
在上面的代码中,我们通过设置XmlWriterSettings.Encoding属性来指定编码方式为UTF-32。这样,生成的XML文件就会以UTF-32编码方式保存。
阅读全文