public static MemoryStream ToXmlMemoryStream <TObj>(this TObj obj, Encoding encoding = null, bool indent = true, bool omitXmlDeclaration = false) //where TObj : class { var type = typeof(TObj); var stream = new MemoryStream(); var startingPosition = stream.Position; var xmlWriterSettings = new XmlWriterSettings { Indent = indent, //следует ли использовать отступ для элементов Encoding = (encoding ?? DefaultEncoding), OmitXmlDeclaration = omitXmlDeclaration //следует ли опустить XML-объявление }; using (var xmlWriter = XmlWriter.Create(stream, xmlWriterSettings)) { //пустое пространство имен при сериализации var xmlSerializerNamespaces = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") }); XmlCacheFactory.XmlSerializer(type).Serialize(xmlWriter, obj, xmlSerializerNamespaces); xmlWriter.Close(); } stream.Position = startingPosition; return(stream); }
public static object FromXml(this Stream source, Type type) { return(XmlCacheFactory.XmlSerializer(type).Deserialize(source)); }