【问题标题】:Override class name for XmlSerialization覆盖 XmlSerialization 的类名
【发布时间】:2012-01-03 16:30:05
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 你为什么不想做简单的选择?出于好奇? (另请注意:使用非平凡构造函数意味着您必须缓存序列化程序,否则会泄漏程序集;基本的 XmlSerializer(Type) 构造函数不会受到此影响)
  • 你是ChannelConfiguration类的所有者,你能用属性装饰它吗?如果是,我可能有一个解决方案。
  • @MarcGravell,也许你是对的,我应该使用包装器
  • @achitaka-san,是的,我是这个类的所有者

标签: c# .net serialization xml-serialization


【解决方案1】:

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

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

}

【讨论】:

  • 当对象是 List 的一部分时,XmlRoot 不起作用...但 XmlType 起作用。这解决了我的问题,谢谢@JordyLangen。
【解决方案2】:

像这样:

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 { } });

【讨论】:

    猜你喜欢
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    相关资源
    最近更新 更多