Convert an Object to XML in C#


private string GetObjectAsXml(object obj)

{

PropertyInfo[] properties =  obj.GetType().GetProperties();

StringBuilder builder = new StringBuilder();

builder.AppendFormat(“<{0}>”, obj.GetType().Name);

foreach (PropertyInfo property in properties)

{

object propertyValue = property.GetValue(obj, null);

builder.AppendFormat(“<{0}>{1}</{0}>”, property.Name, propertyValue);

}

builder.AppendFormat(“</{0}>”, obj.GetType().Name);

return builder.ToString();

}

Advertisements

One thought on “Convert an Object to XML in C#

  1. Another way:

    public T LoadFromXml(string xml)
    {
    XmlSerializer ser = new XmlSerializer(typeof(T));

    StringReader reader = new StringReader(xml);

    object result = ser.Deserialize(reader);

    return (T)result;
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s