Muhammad Tahir Muhammad Tahir - 1 year ago 105
C# Question

How to? XML Serialization of a Class Object

I am trying to Serialize a Class object and store the xml in a string but each time I get an exception message "There was an error generating xml document"

The class object I am trying to serialize is of class:

public class Flow
int _CurrHop = 0;

public int CurrentHop
get { return _CurrHop; }
set { _CurrHop = value; }

int _TotalHops = 0;

public int TotalHops
get { return _TotalHops; }

private List<tblTaskHop> _TaskHops;

[System.Xml.Serialization.XmlArrayItemAttribute(ElementName = "Hop",
IsNullable = false)]
public List<tblTaskHop> TaskHops
get { return _TaskHops; }
public Flow()


public Flow(Int64 TaskID, Int64 RoleID)
_TaskHops = HandleDB.tblTaskHopGetByTaskIDRoleID(TaskID, RoleID);
_TotalHops = TaskHops.Count;


I am using this function to serialize.

public static string SerializeAnObject(object item)

string xmlText;

//Get the type of the object
Type objectType = item.GetType();

//create serializer object based on the object type
XmlSerializer xmlSerializer = new XmlSerializer(objectType);

//Create a memory stream handle the data
MemoryStream memoryStream = new MemoryStream();

//Create an XML Text writer to serialize data to
using (XmlTextWriter xmlTextWriter =
new XmlTextWriter(memoryStream, Encoding.UTF8) { Formatting = Formatting.Indented })

//convert the object to xml data
xmlSerializer.Serialize(xmlTextWriter, item);

//Get reference to memory stream
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;

//Convert memory byte array into xml text
xmlText = new UTF8Encoding().GetString(memoryStream.ToArray());

//clean up memory stream
return xmlText;
catch (Exception e)
return null;

Can anyone help me why I am not able to serialize this class object?

Answer Source

Your serialization method should look like this:

public static string SerializeAnObject(Object item) {
    if (item == null)
        return null;

    var stringBuilder = new StringBuilder();
    var itemType = item.GetType();

    new XmlSerializer(itemType).Serialize(new StringWriter(stringBuilder), item);

    return stringBuilder.ToString();

The function above works when I test it like this:

var test = new Flow();
var xmlString = SerializeAnObject(test);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download