Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override class name for XmlSerialization

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.

like image 961
SiberianGuy Avatar asked Nov 22 '11 09:11

SiberianGuy


People also ask

Which class should be used to serialize an object in XML format?

You have to use XmlSerializer for XML serialization.

Why do we use XML serializer class?

XmlSerializer Class. Serializes and deserializes objects into and from XML documents. The XmlSerializer enables you to control how objects are encoded into XML. XML serialization is the process of converting an object's public properties and fields to a serial format (in this case, XML) for storage or transport.

What is the difference between binary serialization and XML serialization?

Xml Serializer serializes only public member of object but Binary Serializer serializes all member whether public or private. In Xml Serialization, some of object state is only saved but in Binary Serialization, entire object state is saved.


1 Answers

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 { } });
like image 130
Marc Gravell Avatar answered Oct 16 '22 07:10

Marc Gravell