You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#序列化List对象为XML时如何移除XML声明?

在C#中移除List序列化XML时的XML声明

要移除XML声明(比如<?xml version="1.0" encoding="utf-16"?>),核心是通过XmlWriterSettings配置序列化器,禁用声明输出。下面是具体实现步骤和代码示例:

1. 定义要序列化的实体类

假设我们要序列化的List包含自定义对象,先定义实体:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

2. 编写序列化方法,移除XML声明

使用XmlSerializer结合XmlWriterSettings,将OmitXmlDeclaration设为true,同时可按需配置其他格式选项:

public static string SerializeListToXmlWithoutDeclaration<T>(List<T> list)
{
    var serializer = new XmlSerializer(typeof(List<T>));
    var settings = new XmlWriterSettings
    {
        OmitXmlDeclaration = true, // 关键配置:禁用XML声明输出
        Indent = true, // 可选:格式化XML结构,提升可读性
        Encoding = new UTF8Encoding(false) // 可选:指定UTF-8编码且不带BOM
    };

    using (var stringWriter = new StringWriter())
    using (var xmlWriter = XmlWriter.Create(stringWriter, settings))
    {
        // 可选:移除默认生成的XML命名空间
        var namespaces = new XmlSerializerNamespaces();
        namespaces.Add("", "");
        
        serializer.Serialize(xmlWriter, list, namespaces);
        return stringWriter.ToString();
    }
}

3. 调用示例

var people = new List<Person>
{
    new Person { Name = "张三", Age = 25 },
    new Person { Name = "李四", Age = 30 }
};

var xmlResult = SerializeListToXmlWithoutDeclaration(people);
Console.WriteLine(xmlResult);

输出结果会是不带XML声明的XML:

<ArrayOfPerson>
  <Person>
    <Name>张三</Name>
    <Age>25</Age>
  </Person>
  <Person>
    <Name>李四</Name>
    <Age>30</Age>
  </Person>
</ArrayOfPerson>

注意事项

  • 若不需要移除默认命名空间,可删除XmlSerializerNamespaces相关代码;
  • 若要将结果写入文件而非字符串,只需把StringWriter替换为FileStream,配置逻辑保持一致;
  • Encoding配置可根据实际需求调整,比如保留默认编码则可去掉该设置。

内容的提问来源于stack exchange,提问作者user3767641

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 19:27:33