BoapeEsonse
New Member
I'm trying to find a simple way to serialize any object so that only the immediate properties and their "ToString" values are included. In the case of an object coming from a DataContext I want to be able to ignore properties of properties (ie. if a property is a complex object, don't serialize that object as well). This is especially important if the properties are not loaded since it causes an error "Cannot access an object after it has been disposed"...I created the following but it fails when it tries to access a property that wasn't loaded in the original datacontext call.\[code\]string typeString = o.GetType().Name; StringBuilder xml = new StringBuilder(); xml.AppendFormat("<{0}>\r\n", typeString); foreach (PropertyInfo property in o.GetType().GetProperties()) { var propertyValue = http://stackoverflow.com/questions/15536731/property.GetValue(o, null); if (property.GetType() != typeof(System.Data.Linq.Binary) && property.PropertyType.Name !="EntitySet`1" && property.GetCustomAttributes(typeof(XmlIgnoreAttribute), true).Count() == 0) { xml.AppendFormat("<{0}>{1}</{0}>\r\n", property.Name, propertyValue); } } xml.AppendFormat("</{0}>", typeString); return xml.ToString();\[/code\]