.comment-link {margin-left:.6em;}

I Hate Linux

Wednesday, July 06, 2005

Flat XML Serialization

Serialization in .NET rocks! It makes some of ones tasks of constructing an XML file out of values from a class and vice versa so simple.

Recently at work we had a need to send an XML string across the wire without all of the extra hard returns and formatting, however I did not have much luck other doing a quick and dirty Replace() on the string (which was enough for the time being). Later, seeing someone on microsoft.public.dotnet.languages.csharp asking about how to do this... I decided it was time to find a way... unfortunately, Google failed me, running searches such as: 'XmlSerializer format c# flat', 'XML Serializer format', 'Serialize format c#', 'XmlSerializer format c# flat' and many others... all without luck. (Note: those search terms are only here to help Google pick up on this page in case

In order to serialize something normally, you need to create a stream (to resource it will be serialized to (string, file, etc)) that is indirectly used by the serializer. This stream is often wrapped in a stream writer of some sort, often a TextWriter or StringWriter in my case.

If you create a new XmlTextWriter that uses the previously created TextWriter or StringWriter, you can better control the output, nambly by setting the Formatting property of the XmlTextWriter to None.

The following code is an example of how I traditionally serialize a class to a string (albeit stripped down a bit):

StringBuilder serializedOutputStringBuilder = new StringBuilder();
XmlSerializer s = new XmlSerializer( typeof( ClassTypeToBeSerialized ) );
StringWriter w = new StringWriter( serializedOutputStringBuilder ) );
s.Serialize( w, value);
w.Close();

We modify the creation of the StringWriter be created as an parameter for the creation of the XmlTextWriter ala:

StringBuilder serializedOutputStringBuilder = new StringBuilder();
XmlSerializer s = new XmlSerializer( typeof( ClassTypeToBeSerialized ) );
XmlTextWriter w = new XmlTextWriter( new StringWriter( serializedOutputStringBuilder ) );
w.Formatting = Formatting.None;
s.Serialize( w, value);
w.Close();

It's that simple, sure wish I had figured out how to do this a couple of weeks ago instead of having such high quality logic as:

serializedOutput = serializedOutputStringBuilder.ToString().Replace("\r\n","");

Yes, I know that this is a minor discovery and countless others have used it in past, I only offer this write up in the hopes that any others trying to find this method can do so more easily.

0 Comments:

Post a Comment

<< Home