Object Serialization

  • Thread starter Thread starter Stephen J. Shephard
  • Start date Start date
S

Stephen J. Shephard

Hi,
I'm a real fan of serializing and deserializing objects into xml, but it
seems that the xmlserializer only likes to serialize to a file on disk. I'm
sure that's the whole point of serialization (commit to persistent storage),
but I often find myself wishing I could commit an object to an XmlDocument
or resurrect an object from an XmlDocument object and then decide what to do
with it -- save it to disk, commit it to a text field in a database, etc.
Specifically, I'd like to be able to represent an object as xml so I can
store the xml in a database text field.
Can anybody recommend the best way to do this?
 
but I often find myself wishing I could commit an object to an XmlDocument
or resurrect an object from an XmlDocument object and then decide what to do
with it -- save it to disk, commit it to a text field in a database, etc.

Enjoy - other examples left to the reader:

static string SerializeThingToXmlString(object thing)
{
StringWriter stringWriter = new StringWriter();
XmlSerializer serializer = new XmlSerializer(thing.GetType());
serializer.Serialize(stringWriter, thing);
return stringWriter.ToString();
}

static XmlTextReader SerializeThingToXmlTextReader(object thing)
{
MemoryStream ms = new MemoryStream();
XmlSerializer serializer = new XmlSerializer(thing.GetType());
serializer.Serialize(ms, thing);
ms.Seek(0, SeekOrigin.Begin);
return new XmlTextReader(ms);
}

static XmlDocument SerializeThingToXmlDocument(object thing)
{
XmlTextReader reader = SerializeThingToXmlTextReader(thing);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
return doc;
}
 
Hello Stephen,
sure that's the whole point of serialization (commit to persistent
storage),
but I often find myself wishing I could commit an object to an
XmlDocument
or resurrect an object from an XmlDocument object and then decide what
to do
with it -- save it to disk, commit it to a text field in a database,
etc.

There is an overload of XmlSerializer.Serialize that takes a TextWriter object. You *could* do something like this:

public void SaveObject(CustomObject obj)
{
StringBuilder sb = new StringBuilder();
XmlSerializer serializer = new XmlSerializer(typeof(CustomObject));
StringWriter writer = new StringWriter(sb);

serializer.Serialize(writer, obj);
writer.Flush();
writer.Close();

// Do your database stuff here, using sb.ToString() as your serialized object's xml representation
Console.WriteLine(sb.ToString());
}

Deserialization would be the reverse. Meaning that you create a StringReader from a string and pass that into the deserialize method.

HTH.
 
Thanks for the stringwriter example Mickey! That looks like what I need. I
appreciate your help!
S
 
Back
Top