TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Serializing an Object to an XML String

Today I ran into some code on Egghead Cafe to serialize an object to an XML string. The example was wired up using MemoryStream objects, UTF8Encoding, and all kinds of stuff just to get an object serialized into an XML string.
 

public String SerializeObject(Object pObject)

{

    try

    {

        String XmlizedString = null;

        MemoryStream memoryStream = new MemoryStream();

        XmlSerializer xs = new XmlSerializer(typeof(Animal));

        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

        xs.Serialize(xmlTextWriter, pObject);

        memoryStream = (MemoryStream)xmlTextWriter.BaseStream;

        XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());

        return XmlizedString;

    }

    catch (Exception e) { System.Console.WriteLine(e); return null; }

}

 

private String UTF8ByteArrayToString(Byte[] characters)

{

 

    UTF8Encoding encoding = new UTF8Encoding();

    String constructedString = encoding.GetString(characters);

    return (constructedString);

}


Seems like I should just be able to do this...
 

public string GetXml()

{    

    XmlSerializer serializer = new XmlSerializer(typeof(Animal));

    StringBuilder sb = new StringBuilder();

    using(StringWriter writer = new StringWriter(sb))

    {

        serializer.Serialize(writer, this);

        return sb.ToString();

    }

}

Maybe, I'm missing something (set me straight if I am), but am I oversimplifying doing this? As I've posted repeatedly, I'm always looking for good (or better) ways to do things.  :-)


Digg!

posted on Wednesday, February 09, 2005 2:16 AM

Feedback

No comments posted yet.