Override class name for XmlSerialization
Solution 1
Like so:
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 { } });
Note you must cache and re-use this serializer instance.
I will also say that I strongly recommend you use the "wrapper class" approach - simpler, no risk of assembly leakage, and IIRC it works on more platforms (pretty sure I've seen an edge-case where the above behaves differently on some implementations - SL or WP7 or something like that).
If you have access to the type ChannelConfiguration
, you can also just use:
[XmlType("Channel")]
public class ChannelConfiguration
{...}
var xmlSerializer = new XmlSerializer(typeof(List<ChannelConfiguration>),
new XmlRootAttribute("Channels"));
xmlSerializer.Serialize(Console.Out,
new List<ChannelConfiguration> { new ChannelConfiguration { } });
Solution 2
This should do the trick, if I remember correctly.
[XmlType("Channel")]
public class ChannelConfiguration {
}
SiberianGuy
Updated on July 15, 2022Comments
-
SiberianGuy almost 2 years
I need to serialize IEnumerable. At the same time I want root node to be "Channels" and second level node - Channel (instead of ChannelConfiguration).
Here is my serializer definition:
_xmlSerializer = new XmlSerializer(typeof(List<ChannelConfiguration>), new XmlRootAttribute("Channels"));
I have overriden root node by providing XmlRootAttribute but I haven't found an option to set Channel instead of ChannelConfiguration as second level node.
I know I can do it by introducing a wrapper for IEnumerable and using XmlArrayItem but I don't want to do it.
-
Nevyn over 9 yearsWhen the object is part of a List<myObjects>, XmlRoot doesn't work...but XmlType DOES. This fixed my issue, Thanks @JordyLangen.