XmlSerializer Limitations and Tutorials

In the current version of C#/XAML for HTML5, the "XmlSerializer" class has the following limitations:

  • You must add the attribute "[DataContract]" to any type that you want to serialize/deserialize.
  • The following types are not yet supported:
    • Nullables
    • byte[]
  • The root of serialized objects must not be enumerable (support for the "ArrayOf" element in an XML is under development). You can however use enumerables if they are not the root of the XML.
  • Custom namespaces are not yet supported

We are working to add support for all of the above features as soon as possible. Please make sure to vote for your most wanted features on http://cshtml5.uservoice.com


Please use the following code to serialize an object:

var serializer = new XmlSerializer(typeof(ClassToSerialize));
var stream = new MemoryStream(); serializer.Serialize(stream, _classToSerialize);
stream.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(stream);
var serializedXml = reader.ReadToEnd();

Please use the following code to deserialize an object:

var deserializer = new XmlSerializer(typeof(ClassToSerialize));
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(serializedXml));
var xmlReader = XmlReader.Create(memoryStream);
ClassToSerialize deserializedObject = (ClassToSerialize)deserializer.Deserialize(xmlReader);

Example of serializable class:

public class ClassToSerialize
    public string TextField { get; set; }
    public DateTime DateField { get; set; }
    public Guid GuidField { get; set; }
    public bool BooleanField { get; set; }

Common issues and solutions

  • If you get the error "Could not find the name 'Xml' in the namespace 'Microsoft'.", you must verify that you have added the attribute "[DataContract]" to the class that you want to serialize/deserialize.
  • If you get the error "XmlSerializer assembly does not contain a serializer for type '...'", you must verify that the said type is publicly accessible, and that it has the [DataContract] attribute. If the error persists, please look at the output of the compilation (in the Output pane of Visual Studio) for possible hints (look especially at the "SerializationAssembliesGenerator" part).


For any question, please post a message on the forums or contact us at support@cshtml5.com