This is an extension method that serializes any object to xml. Note that it is “null resistant” in that if the target is null, the extension does not throw an object-not-set-to-an-instance exception, but instead simply returns null.
public static string ToXmlString(this T item) where T : class { if (item == null) { return null; } string xml; using (var stream = new MemoryStream()) using (var writer = XmlWriter.Create(stream)) { new XmlSerializer(item.GetType()).Serialize(writer, item); xml = Encoding.UTF8.GetString(stream.ToArray()); } return xml; }
