Click here to Skip to main content
15,886,519 members
Articles / Programming Languages / C# 3.5
Tip/Trick

Serialize objects into XML strings

Rate me:
Please Sign up or sign in to vote.
4.00/5 (2 votes)
31 Mar 2014CPOL 30K   9   2

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#]

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]

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer
Jordan Jordan
I'm a computer engineer, interested in hardware, software and security.

Always trying to learn new topics, to seek a decent computer engineering career!

Comments and Discussions

 
QuestionLimitations of the built in XML Serializer Pin
not_starman31-Mar-14 9:31
not_starman31-Mar-14 9:31 
AnswerRe: Limitations of the built in XML Serializer Pin
Abdallah Al-Dalleh31-Mar-14 20:10
Abdallah Al-Dalleh31-Mar-14 20:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.