Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Serialize objects into XML strings

0.00/5 (No votes)
31 Mar 2014 1  

If you want to serialize objects directly into strings without the need of a FileStream object or any stream object, the StringReader and StringWriter classes will come in handy. Assume you want to serialize a List of integers, you may do the serialization and deserialization as this:

[C#]

public static string DataSerialize(List<int> myList)
{
    StringWriter sw = new StringWriter();
    XmlSerializer s = new XmlSerializer(myList.GetType());
    s.Serialize(sw, myList);
    return sw.ToString();
}

public static List<int> DataDeserialize(string data)
{
    XmlSerializer xs = new XmlSerializer(typeof(List<int>));
    List<int> newList = (List<int>)xs.Deserialize(new StringReader(data));
    return newList;
} 

[VB.NET]

Public Shared Function DataSerialize(ByVal myList As List(Of int)) As String
    Dim sw As StringWriter = New StringWriter()
    Dim s As New XmlSerializer(myList.GetType())
    s.Serialize(sw, myList)
    Return sw.ToString()
End Function

Public Shared Function DataDeserialize(ByVal data As String) As List(Of int)
    Dim xs As New XmlSerializer(GetType(List(Of int)))
    Dim newList As List(Of int) = CType(xs.Deserialize(New StringReader(data)), List(Of int))
    Return newList
End Function 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here