Skip to content

Instantly share code, notes, and snippets.

@postb99
Created August 8, 2019 12:15
Show Gist options
  • Select an option

  • Save postb99/f9867f323ddb25da0f272d7a7b1522e1 to your computer and use it in GitHub Desktop.

Select an option

Save postb99/f9867f323ddb25da0f272d7a7b1522e1 to your computer and use it in GitHub Desktop.
XML serialization of any class you cannot annotate
// For example classes generated by adding a reference to a WCF service.
// IEnumerable and arrays are tricky to serialize to xml, so here is the tip.
// First, I build a dictionary and put xml serialiers instance like this:
// _xmlSerializers.Add(typeof(SomeType), new XmlSerializer(typeof(SomeType), "a namespace"));
// _xmlSerializers.Add(typeof(List<SomeType>), new XmlSerializer(typeof(List<SomeType>), "a namespace"));
// Then te code to serialize a class:
string serialized = null;
bool serializerFound = false;
using (var xwriter = new Utf8StringWriter())
{
if (!_xmlSerializers.ContainsKey(@object.GetType()))
{
serializerFound = false;
IEnumerable<dynamic> objectAsIenumerable = @object as IEnumerable<dynamic>;
if (objectAsIenumerable != null)
{
// create a typed list from the enumeration
Type listItemType = null;
if (@object.GetType().GetGenericArguments().Length > 0)
listItemType = @object.GetType().GetGenericArguments()[0]; // IEnumerable<T>
else
listItemType = @object.GetType().GetElementType(); // [T]
Type genericListType = typeof(List<>);
Type typedListType = genericListType.MakeGenericType(listItemType);
dynamic typedList = Activator.CreateInstance(typedListType);
IEnumerator<dynamic> enumerator = objectAsIenumerable.GetEnumerator();
while (enumerator.MoveNext())
typedList.Add(enumerator.Current);
if (!_xmlSerializers.ContainsKey(typedListType))
throw new Exception($"No xml serializer defined for type {typedListType}");
_xmlSerializers[typedListType].Serialize(xwriter, typedList);
serializerFound = true;
serialized = xwriter.ToString();
}
}
else
{
_xmlSerializers[@object.GetType()].Serialize(xwriter, @object);
serializerFound = true;
serialized = xwriter.ToString();
}
}
if (!serializerFound)
throw new Exception($"No xml serializer defined for type {@object.GetType()}");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment