views:

151

answers:

2

I am writing common functions to serialize the given object and List<object> as follows

public string SerializeObject(Object pObject)// for given object
{
    try
    {
        String XmlizedString = null;
        MemoryStream memoryStream = new MemoryStream();
        XmlSerializer xs = new XmlSerializer(typeof(pObject));
        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; }
}

public string SerializeObject(List<Object> pObject)// for given List<object>
{
    try
    {
        String XmlizedString = null;
        MemoryStream memoryStream = new MemoryStream();
        XmlSerializer xs = new XmlSerializer(typeof(pObject));
        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; }
}

first one is working fine. If I pass any type, it is successfully returning xml string.

CORRECTION: Compilation error has occurred for second one (Error: cannot convert from List<MyType> to List<object>.

I rewrite the second one as follows which solves my problem. Now it is serializing the given List<generic types>.

private string SerializeObject<T>(T source)
{
    MemoryStream memoryStream = new MemoryStream();
    XmlSerializer xs = new XmlSerializer(typeof(T));
    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
    xs.Serialize(xmlTextWriter, source);
    memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
    string XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
    return XmlizedString;
}
+1  A: 

http://weblogs.asp.net/rajbk/archive/2009/10/04/xmlserializer-and-invalid-xml.aspx

Raj Kaimal
@Raj: Thank you
afin
+2  A: 

I have tried your two functions without much trouble. The only thing I changed was this line:

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

to this:

XmlSerializer xs = new XmlSerializer(pObject.GetType());

typeof() requires an actual type whereas GetType() returns the type of the object.

quagland
@quagland: sorry, my question has been corrected. I got compilation error for second one, since I passed List<MyType> as a input parameter. I need this common function should support all types.
afin