Wednesday, September 15, 2010

How to serialize object to a string as XML and deserialize XML string to an object (Useful when saving multiple selections to database fileds like checkbox selections)

When saving values of fields where we have multiple selections, it is usual way to save as comma separated values in a text field in the database. However, this make extreamly hard to query and edit those values. So as an alternative way we can serialize the object to a string of XML and then save the string of XML to a XML database field where we can perform X-Path Queries. (For SQL Server X-Path - Please see this article). Then when retrieving values from the database, we can read the XML string from database and desrialize XML string in to our respective object.
This example demonstrate how to serialize and deserialize List<string> object to XML string and deserialize XML string to a List<string> object.
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
 
    List<string> values = new List<string>();
    for (int i = 0; i < 10; i++)
        values.Add("Value " + i);
 
    string xml = this.Serialize(values);
    ///
    /// Save database as XML so that you can do a XPath Query
    ///
 
 
    ///
    /// Get xml string and convert it in to a List<string>
    ///
    List<string> savedValues = this.Deserialize(xml);
 
}
private string Serialize(List<string> values)
{
    XmlSerializer serializer = new XmlSerializer(typeof(List<string>));
    MemoryStream stream = new MemoryStream();
    XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
    serializer.Serialize(writer, values);
    stream = (MemoryStream)writer.BaseStream;
    UTF8Encoding utf8 = new UTF8Encoding();
    string xml = utf8.GetString(stream.ToArray());
    return xml;
}
private List<string> Deserialize(string xml)
{
    XmlSerializer serializer = new XmlSerializer(typeof(List<string>));
    UTF8Encoding utf8 = new UTF8Encoding();
    byte[] bytes = utf8.GetBytes(xml);
    MemoryStream stream = new MemoryStream(bytes);
    XmlTextReader reader = new XmlTextReader(stream);
    List<string> values = (List<string>)serializer.Deserialize(reader);
    return values;
}

No comments:

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...