Advertisement
Borrisholt

XML Serialize/DeSerialize

Jan 25th, 2016
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.59 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Xml;
  8. using System.Xml.Serialization;
  9.  
  10. namespace ConsoleApplication3
  11. {
  12.  
  13.     public static class XmlExtension
  14.     {
  15.         public static T DeSerialize<T>(this T value, Byte[] bytes)
  16.         {
  17.             if (value == null)
  18.                 return default(T);
  19.  
  20.             var xmlserializer = new XmlSerializer(typeof(T));
  21.             var xmlSerializerNamespaces = new XmlSerializerNamespaces();
  22.             xmlSerializerNamespaces.Add(string.Empty, string.Empty);
  23.  
  24.  
  25.             using (var reader = new MemoryStream(bytes))
  26.             {
  27.                 value = (T)xmlserializer.Deserialize(reader);
  28.             }
  29.  
  30.             return value;
  31.         }
  32.  
  33.         public static string Serialize<T>(this T value)
  34.         {
  35.             if (value == null)
  36.                 return string.Empty;
  37.  
  38.             var xmlserializer = new XmlSerializer(typeof(T));
  39.             var xmlSerializerNamespaces = new XmlSerializerNamespaces();
  40.             xmlSerializerNamespaces.Add(string.Empty, string.Empty);
  41.  
  42.             using (var stringWriter = new StringWriter())
  43.             {
  44.                 using (var writer = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true, Encoding = Encoding.UTF8 }))
  45.                 {
  46.                     xmlserializer.Serialize(writer, value, xmlSerializerNamespaces);
  47.                     return stringWriter.ToString();
  48.                 }
  49.             }
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement