Serialize and deserialize objects as Xml using generic types in C# 2.0

I've been using Object<>Xml serialization in.NET based on for a while. I decided to enhance it a tad bit with some generics, so I could use it more broadly. Here's what I came up with:

using System.Collections.Generic;using System.Text;using System.Xml;using System.IO;using System.Xml.Serialization;

///

/// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String./// /// Unicode Byte Array to be converted to String /// String converted from Unicode Byte Array private static string UTF8ByteArrayToString(byte[] characters) {    UTF8Encoding encoding = new UTF8Encoding;    string constructedString = encoding.GetString(characters);    return (constructedString); }

///

/// Converts the String to UTF8 Byte array and is used in De serialization/// /// /// private static Byte[] StringToUTF8ByteArray(string pXmlString) {    UTF8Encoding encoding = new UTF8Encoding;    byte[] byteArray = encoding.GetBytes(pXmlString);    return byteArray; }

///

/// Serialize an object into an XML string/// /// /// /// public static string SerializeObject(T obj) {    try   {       string xmlString = null;       MemoryStream memoryStream = new MemoryStream;       XmlSerializer xs = new XmlSerializer(typeof(T));       XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);       xs.Serialize(xmlTextWriter, obj);       memoryStream = (MemoryStream)xmlTextWriter.BaseStream;       xmlString = UTF8ByteArrayToString(memoryStream.ToArray);      return xmlString;    }   catch   {       return string.Empty;    } }

///

/// Reconstruct an object from an XML string/// /// /// public static T DeserializeObject(string xml) {    XmlSerializer xs = new XmlSerializer(typeof(T));    MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xml));    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);    return (T)xs.Deserialize(memoryStream); }

This article is part of the GWB Archives. Original Author: Paul Whitaker

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.