EvilZone

Programming and Scripting => .NET Framework => : xor May 19, 2015, 02:12:42 AM

: [C#] XML Serialize/Deserialize - Stream Extension Class
: xor May 19, 2015, 02:12:42 AM
:
    public static class XmlSerializerExtensions
    {
        public static T LoadFromXml<T>(this Stream stream)
        {
            var type = typeof(T);
            var serializer = new XmlSerializer(type);
            return (T)serializer.Deserialize(stream);
        }


        public static void SaveToXml<T>(this Stream stream, T obj)
        {
            var type = typeof (T);
            var serializer = new XmlSerializer(type);
            serializer.Serialize(stream, obj);
        }
    }
: Re: [C#] XML Serialize/Deserialize - Stream Extension Class
: Xires May 21, 2015, 12:09:05 PM
I think I would overload SaveToXml() to serialize to a string and return that string.  Has more cookies.
: Re: [C#] XML Serialize/Deserialize - Stream Extension Class
: ArkPhaze May 23, 2015, 03:05:20 AM
There's absolutely no safety behind these functions to check if the data is even serializable or not. You're missing out on a lot of useful functionality.
: Re: [C#] XML Serialize/Deserialize - Stream Extension Class
: xor May 27, 2015, 06:52:53 PM
You're right ArkPhaze. Exception handling is to be done by the caller.
As for overloads, that's user preference.


This function builds upon Streams as a means of quickly reading / writing to File Systems, Memory, Network. It's by no means designed for production systems, though I don't see the inherent safety issues? So any enlightenment would be nice.


-- xor
: Re: [C#] XML Serialize/Deserialize - Stream Extension Class
: ArkPhaze May 31, 2015, 01:05:06 AM
I'm talking about taking on a similar TryParse() paradigm, and these 2 methods:
https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.candeserialize%28v=vs.110%29.aspx (https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.candeserialize%28v=vs.110%29.aspx)
https://msdn.microsoft.com/en-us/library/system.type.isserializable%28v=vs.110%29.aspx (https://msdn.microsoft.com/en-us/library/system.type.isserializable%28v=vs.110%29.aspx)

These should probably not be done on the caller side for best design.