DeSerializing an object

G

Guest

Hi,

I have a simple class named DistributionSelections which stores two enums
and a dataset. I want to persist the object to a database for later
retrieval.

HERE IS THE CODE USED TO PERSIST THE OBJECT IN THE DB:
//====================================================
XmlSerializer x = new XmlSerializer(distributionselections.GetType());
StringWriter sw=new StringWriter(new StringBuilder());
x.Serialize(sw,distributionselections);
LogDB.LogEvent(sw.ToString());
//====================================================

This seems to work fine.

HERE IS THE CODE USED TO RECONSTITUTE THE OBJECT:
//====================================================
foreach(DataRow row in table.Rows)
{
XmlSerializer serializer = new XmlSerializer(typeof(DistributionSelections));

XmlTextReader xtr = new XmlTextReader( new
StringReader(row["Comment"].ToString()));

DistributionSelections selections=(DistributionSelections)
serializer.Deserialize(xtr);

//do something with the object.
}
//====================================================

When trying to reconstitue the object using the Deserialize method, I get an
error complaining that there is an unexpected tokey, the expected tokey is
'EndElement'.

I had expected object serialization/deserialization to be a bit easier. Am
I missing something?

Thank you very much for any help.
-Keith
 
W

William Stacey [MVP]

Normally when I approach issues, I take all the crude out of the picture.
For example, the db processing here has nothing to do with serialization, so
remove it till you get your serializer working. I am guessing your input
string is not right. Test it directly with your object like so:

// Serialize.
KeyValue kv = new KeyValue("123", "Hello");
XmlSerializer x = new XmlSerializer(typeof(KeyValue));
string xmlString;
using( StringWriter sw = new StringWriter() )
{
x.Serialize(sw, kv);
xmlString = sw.ToString();
}

// Deserialize.
XmlSerializer ser = new XmlSerializer(typeof(KeyValue));
using (StringReader sr = new StringReader(xmlString))
{
KeyValue kv2 = (KeyValue)ser.Deserialize(sr);
Console.WriteLine("Key:" + kv2.Key);
Console.WriteLine("Value:" + kv2.Value);
}

public struct KeyValue
{
public string Key;
public string Value;

public KeyValue(string key, string value)
{
this.Key = key;
this.Value = value;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top