Saturday, September 6, 2014

Serialize object to XML with custom object with indentation


Serialize object to XML with custom object with indentation 


If you want to serialize object without including the tag XMLInclude and with nice indentation and formatting use the below method  

 

public static String SerializeObject(object objectToSerialize, List<Type> knownTypes)

        {

            XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType(), knownTypes.ToArray());

            var stringBuilder = new StringBuilder();

            var xmlTextWriter = XmlTextWriter.Create(stringBuilder, new XmlWriterSettings { NewLineChars = "\r\n", Indent = true });

            xmlSerializer.Serialize(xmlTextWriter, objectToSerialize);

            return stringBuilder.ToString();

        }


Happy programming :)

No comments:

Post a Comment