覆盖XmlSerialization的类名

时间:2011-11-22 09:07:24

标签: c# .net serialization xml-serialization

我需要序列化IEnumerable。同时我希望根节点为“Channels”和第二级节点 - Channel(而不是ChannelConfiguration)。

这是我的序列化程序定义:

_xmlSerializer = new XmlSerializer(typeof(List<ChannelConfiguration>), new XmlRootAttribute("Channels"));

我通过提供XmlRootAttribute来覆盖根节点,但是我没有找到将Channel而不是ChannelConfiguration设置为第二级节点的选项。

我知道我可以通过为IEnumerable引入一个包装器并使用XmlArrayItem来实现它,但我不想这样做。

2 个答案:

答案 0 :(得分:17)

像这样:

XmlAttributeOverrides or = new XmlAttributeOverrides();
or.Add(typeof(ChannelConfiguration), new XmlAttributes
{
    XmlType = new XmlTypeAttribute("Channel")
});
var xmlSerializer = new XmlSerializer(typeof(List<ChannelConfiguration>), or,
     Type.EmptyTypes, new XmlRootAttribute("Channels"), "");
xmlSerializer.Serialize(Console.Out,
     new List<ChannelConfiguration> { new ChannelConfiguration { } });

请注意,必须缓存并重新使用此序列化程序实例。

我还会说我强烈建议你使用“包装类”方法 - 更简单,没有组装泄漏的风险,IIRC它可以在更多平台上工作(非常确定我已经看到了上述行为的边缘情况在某些实现上有所不同 - SL或WP7或类似的东西。)

如果您有权访问ChannelConfiguration类型,您也可以使用:

[XmlType("Channel")]
public class ChannelConfiguration
{...}

var xmlSerializer = new XmlSerializer(typeof(List<ChannelConfiguration>),
     new XmlRootAttribute("Channels"));
xmlSerializer.Serialize(Console.Out,
     new List<ChannelConfiguration> { new ChannelConfiguration { } });

答案 1 :(得分:12)

如果我没记错的话,这应该可以解决问题。

[XmlType("Channel")] 
public class ChannelConfiguration {

}