Click here to Skip to main content
11,412,526 members (70,273 online)
Click here to Skip to main content

Serialize objects into XML strings

, 31 Mar 2014 CPOL
Rate this:
Please Sign up or sign in to vote.

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

Share

About the Author

Abdallah Al-Dalleh
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_starman at 31-Mar-14 10:31
membernot_starman31-Mar-14 10:31 
AnswerRe: Limitations of the built in XML Serializer Pin
Abdallah Al-Dalleh at 31-Mar-14 21:10
memberAbdallah Al-Dalleh31-Mar-14 21:10 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150427.1 | Last Updated 31 Mar 2014
Article Copyright 2014 by Abdallah Al-Dalleh
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid