可通过XmlRootAttribute指定序列化根元素名称,支持编译时标记类或运行时传入构造函数;还可设置命名空间、IsNullable等属性;XmlElementAttribute不能用于修改根名。

可以通过 XmlRootAttribute 为 XmlSerializer 指定序列化时的根元素名称,这是最直接、标准的方式。
使用 XmlRootAttribute 标记类
在要序列化的类上添加 [XmlRoot("自定义名称")] 特性,即可覆盖类名作为默认根名的行为。
例如:
[XmlRoot("PersonInfo")]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
序列化后 XML 的根元素将变为 ,而非默认的 。
运行时通过 XmlRootAttribute 构造函数传入
若无法修改类定义(如第三方类),可在创建 XmlSerializer 实例时传入 XmlRootAttribute:
- 构造
XmlRootAttribute并设置ElementName - 将该实例传给
XmlSerializer(Type, XmlRootAttribute)构造函数
示例:
var root = new XmlRootAttribute("CustomerData");
var serializer = new XmlSerializer(typeof(Person), root);
var person = new Person { Name = "Alice", Age = 30 };
serializer.Serialize(Console.Out, person);
// 输出:Alice 30
注意命名空间与其它属性
XmlRootAttribute 还支持控制命名空间、是否生成 xsi:type 等:
-
Namespace:指定根元素的 XML 命名空间 -
IsNullable:影响xsi:nil属性输出 -
DataType:用于指定 XSD 数据类型(如 "string")
例如:[XmlRoot("Item", Namespace = "http://example.com/ns")] 会生成带命名空间前缀或 xmlns 声明的根元素。
不推荐:仅靠 XmlElementAttribute 改根名
[XmlElement] 只作用于**成员字段/属性**,不能改变整个对象序列化的根名。试图在类上误用它不会生效,需明确区分 XmlRoot(针对根)和 XmlElement(针对子元素)。










