Geeks With Blogs
Scott Wojan DotRant BLOG

So I've found these to be useful on a couple of projects, hopefully you will also

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using System.Xml;
  6. using System.Xml.Serialization;
  7.  
  8. public static class XmlExtensionMethods
  9. {
  10.     private static readonly Dictionary<Type, XmlSerializer> Serializers;
  11.     static XmlExtensionMethods()
  12.     {
  13.         Serializers = new Dictionary<Type, XmlSerializer>();
  14.     }
  15.  
  16.     private static XmlSerializer GetSerializer(Type type)
  17.     {
  18.         //If it exists, return it
  19.         if ((Serializers.ContainsKey(type)))
  20.         {
  21.             return Serializers[type];
  22.         }
  23.         //If not, create it, add it to the list and return it.
  24.         var xmlSerializer = new XmlSerializer(type);
  25.         Serializers.Add(type, xmlSerializer);
  26.         return xmlSerializer;
  27.     }
  28.  
  29.     /// <summary>
  30.     /// Serializes the object to XML using the given xml writer settings.
  31.     /// </summary>
  32.     /// <param name="obj"></param>
  33.     /// <param name="xmlWriterSettings"></param>
  34.     /// <returns></returns>
  35.     public static string ToXml<T>(this T obj, XmlWriterSettings xmlWriterSettings)
  36.     {
  37.         if (Equals(obj, default(T)))
  38.         {
  39.             return String.Empty;
  40.         }
  41.  
  42.         using (var memoryStream = new MemoryStream())
  43.         {
  44.             var xmlSerializer = GetSerializer(obj.GetType());
  45.  
  46.             //Remove the xmlns attribute.
  47.             var xmlnsEmpty = new XmlSerializerNamespaces();
  48.             xmlnsEmpty.Add(String.Empty, String.Empty);
  49.  
  50.             using (var xmlTextWriter = XmlWriter.Create(memoryStream, xmlWriterSettings))
  51.             {
  52.                 xmlSerializer.Serialize(xmlTextWriter, obj, xmlnsEmpty);
  53.                 memoryStream.Seek(0, SeekOrigin.Begin); //Rewind the Stream.
  54.             }
  55.  
  56.             var xml = xmlWriterSettings.Encoding.GetString(memoryStream.ToArray());
  57.             return xml;
  58.         }
  59.     }
  60.  
  61.     /// <summary>
  62.     /// Serializes the object to XML, with or without the declaration.
  63.     /// </summary>
  64.     /// <param name="obj"></param>
  65.     /// <param name="omitXmlDeclaration">Gets or sets a value indicating whether to write an XML declaration.</param>
  66.     /// <returns></returns>
  67.     public static string ToXml<T>(this T obj, bool omitXmlDeclaration)
  68.     {
  69.         return obj.ToXml(new XmlWriterSettings
  70.         {
  71.             Encoding = Encoding.UTF8,
  72.             OmitXmlDeclaration = omitXmlDeclaration
  73.         });
  74.     }
  75.  
  76.     /// <summary>
  77.     /// Serializes the object to XML
  78.     /// </summary>
  79.     /// <param name="obj"></param>
  80.     /// <returns></returns>
  81.     public static string ToXml<T>(this T obj)
  82.     {
  83.         return obj.ToXml(false);
  84.     }
  85.  
  86.     /// <summary>
  87.     /// Deserializes the object from xml.
  88.     /// </summary>
  89.     /// <typeparam name="T"></typeparam>
  90.     /// <param name="xml"></param>
  91.     /// <returns></returns>
  92.     public static T FromXml<T>(this string xml)
  93.     {
  94.         var s = GetSerializer(typeof(T));
  95.         var settings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Auto };
  96.         using (var stringReader = new StringReader(xml))
  97.         {
  98.             using (var xmlReader = XmlReader.Create(stringReader, settings))
  99.             {
  100.                 var obj = s.Deserialize(xmlReader);
  101.                 return (T)obj;
  102.             }
  103.         }
  104.     }
  105. }

 

The following code...

  1. [Serializable]
  2. public class TestClass
  3. {
  4.     public DateTime? DateSent { get; set; }
  5.     public string SomeTextValue { get; set; }
  6.     public decimal SomeDecimalValue { get; set; }
  7. }
  8.  
  9. class Program
  10. {
  11.     static void Main(string[] args)
  12.     {
  13.         var testClass = new TestClass
  14.                             {
  15.                                 DateSent = DateTime.Now,
  16.                                 SomeDecimalValue = 22.33m,
  17.                                 SomeTextValue = "This is a test"
  18.                             };
  19.  
  20.         Console.WriteLine(testClass.ToXml());
  21.         Console.WriteLine(testClass.ToXml(true));
  22.         var xml = testClass.ToXml(new XmlWriterSettings
  23.                                          {
  24.                                              Indent = true,
  25.                                              Encoding = Encoding.ASCII
  26.                                          });
  27.         Console.WriteLine(xml);
  28.  
  29.  
  30.         Console.ReadKey();
  31.     }
  32. }

 

Would produce:

  1. <?xml version="1.0" encoding="utf-8"?><TestClass><DateSent>2011-05-18T08:32:37.9236147-05:00</DateSent><SomeTextValue>This is a test</SomeTextValue><SomeDecimalValue>22.33</SomeDecimalValue></TestClass>
  2.  
  3. <TestClass><DateSent>2011-05-18T08:32:37.9236147-05:00</DateSent><SomeTextValue>This is a test</SomeTextValue><SomeDecimalValue>22.33</SomeDecimalValue></TestClass>
  4.  
  5. <?xml version="1.0" encoding="us-ascii"?>
  6. <TestClass>
  7.   <DateSent>2011-05-18T08:34:41.8800091-05:00</DateSent>
  8.   <SomeTextValue>This is a test</SomeTextValue>
  9.   <SomeDecimalValue>22.33</SomeDecimalValue>
  10. </TestClass>

 

 

 

Posted on Wednesday, May 18, 2011 11:47 AM | Back to top

Copyright © Scott Wojan | Powered by: GeeksWithBlogs.net