Serialize generic object to xml format in C# and VB

Generic class that allows you to serialize any object into xml format. Usefull for debugging purposes or log info, for instance for request/response objects when making request to external services.

For json serializer check Newtonsoft library.

C#


/// 
/// Serialize generic object to xml and print string
/// 
/// 
/// /// 
/// 
public static string XMLSerializer(this T value)
{
    if (value == null)
    {
        return string.Empty;
    }
    try
    {
        var xmlserializer = new XmlSerializer(typeof(T));
        var stringWriter = new StringWriter();
        using (var writer = XmlWriter.Create(stringWriter))
        {
            xmlserializer.Serialize(writer, value);
            return stringWriter.ToString();
        }
    }
    catch (Exception ex)
    {
        throw new Exception("An error occurred", ex);
    }
}


VB
''' 
    ''' Serialize generic object to xml and print string
    ''' 
    ''' 
    ''' ''' 
    ''' 
    Public Shared Function XMLSerializer(Of T)(value As T) As String
        If value Is Nothing Then
            Return String.Empty
        End If
        Try
            Dim xmlserial = New XmlSerializer(GetType(T))
            Dim stringWriter = New StringWriter()
            Using writer = XmlWriter.Create(stringWriter)
                xmlserial.Serialize(writer, value)
                Return stringWriter.ToString()
            End Using
        Catch ex As Exception
            Throw New Exception("An error occurred", ex)
        End Try
    End Function

Comments