Sib*_*Guy 10 .net c# serialization xml-serialization
我需要序列化IEnumerable.同时我希望根节点为"Channels"和第二级节点 - Channel(而不是ChannelConfiguration).
这是我的序列化程序定义:
_xmlSerializer = new XmlSerializer(typeof(List<ChannelConfiguration>), new XmlRootAttribute("Channels"));
Run Code Online (Sandbox Code Playgroud)
我通过提供XmlRootAttribute覆盖了根节点,但是我没有找到将Channel而不是ChannelConfiguration设置为第二级节点的选项.
我知道我可以通过引入IEnumerable的包装器并使用XmlArrayItem来实现它,但我不想这样做.
Mar*_*ell 18
像这样:
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 { } });
Run Code Online (Sandbox Code Playgroud)
请注意,您必须缓存并重新使用此序列化程序实例.
我还要说我强烈建议你使用"包装器类"方法 - 更简单,没有组装泄漏的风险,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 { } });
Run Code Online (Sandbox Code Playgroud)
Jor*_*gen 12
如果我没记错的话,这应该可以解决问题.
[XmlType("Channel")]
public class ChannelConfiguration {
}
Run Code Online (Sandbox Code Playgroud)