Save an object to Xml. - CSharp System.Xml

CSharp examples for System.Xml:XML Serialization

Description

Save an object to Xml.

Demo Code


using System.Text;
using System.Reflection;
using System.Xml;
using System.Collections.Generic;
using System.Collections;
using System.Net;
using System.Drawing;
using System;//from  w  w w  .java 2s . c o m

public class Main{
        /// <summary>
      /// Save an object to Xml.
      /// </summary>
      /// <param name="value">The object to serialize.</param>
      /// <param name="writer">The XmlWriter object to save to.</param>
      public static void SaveToXml(object value, XmlWriter writer)
      {
         Type type = value.GetType();

         XmlElementNameAttribute[] xmlElementNameAttributes = (XmlElementNameAttribute[])type.GetCustomAttributes(typeof(XmlElementNameAttribute), true);
         string elementName = (xmlElementNameAttributes.Length > 0 ? xmlElementNameAttributes[0].XmlElementName : type.Name);

         writer.WriteStartElement(elementName);

         PropertyInfo[] properties = type.GetProperties();
         foreach (PropertyInfo property in properties)
         {
            Type propertyType = property.PropertyType;

            XmlIgnoreAttribute[] ignoreAttributes = (XmlIgnoreAttribute[])property.GetCustomAttributes(typeof(XmlIgnoreAttribute), true);
            if (ignoreAttributes.Length == 0)
            {
               XmlAttributeNameAttribute[] xmlAttributeNameAttributes = (XmlAttributeNameAttribute[])property.GetCustomAttributes(typeof(XmlAttributeNameAttribute), true);
               string attributeName = (xmlAttributeNameAttributes.Length > 0 ? xmlAttributeNameAttributes[0].XmlAttributeName : property.Name);
               object propertyValue = property.GetValue(value, null);
               if (propertyValue != null)
               {
                  XmlHasChildElementsAttribute[] xmlHasChildElementsAttributes = (XmlHasChildElementsAttribute[])propertyType.GetCustomAttributes(typeof(XmlHasChildElementsAttribute), true);
                  if ((xmlHasChildElementsAttributes.Length > 0) && (xmlHasChildElementsAttributes[0].HasChildElements))
                  {
                     SaveToXml(propertyValue, writer);
                  }
                  else
                  {
                     XmlCollectionAttribute[] xmlCollectionAttributes = (XmlCollectionAttribute[])property.GetCustomAttributes(typeof(XmlCollectionAttribute), true);
                     if (xmlCollectionAttributes.Length > 0)
                     {
                        if ((propertyValue is IList == false))
                        {
                           throw new Exception("Property marked as XmlCollection but does not implement IList.");
                        }

                        XmlCollectionAttribute xmlCollectionAttribute = xmlCollectionAttributes[0];
                        writer.WriteStartElement(xmlCollectionAttribute.CollectionElementName);

                        IList listValue = (IList)propertyValue;
                        foreach (object childValue in listValue)
                        {
                           SaveToXml(childValue, writer);
                        }

                        writer.WriteEndElement();

                     }
                     else
                     {
                        writer.WriteAttributeString(attributeName, (propertyValue != null ? XmlHelper.ToString(propertyValue) : String.Empty));
                     }
                  }
               }
            }
         }

         writer.WriteEndElement();
      }
        /// <summary>
      /// Save an object to Xml.
      /// </summary>
      /// <param name="value">The object to serialize.</param>
      /// <param name="fileName">The file to save to.</param>
      public static void SaveToXml(object value, string fileName)
      {
         XmlWriterSettings writerSettings = new XmlWriterSettings();
         writerSettings.Indent = true;
         writerSettings.NewLineOnAttributes = true;
         writerSettings.Encoding = Encoding.UTF8;

         XmlWriter writer = XmlWriter.Create(fileName, writerSettings);

         SaveToXml(value, writer);

         writer.Close();
      }
        /// <summary>
      /// 
      /// </summary>
      /// <typeparam name="T"></typeparam>
      /// <param name="value"></param>
      /// <returns></returns>
      public static string ToString<T>(T value)
      {
         object valueObject = value;

         Type type = value.GetType();
         string stringValue;

         if (type.IsEnum)
         {
            stringValue = valueObject.ToString();
         }
         else
         {
            switch (type.Name)
            {
               case "Point":
                  {
                     Point point = (Point)valueObject;
                     stringValue = string.Format("{0}, {1}", point.X, point.Y);
                     break;
                  }

               case "Color":
                  {
                     Color color = (Color)valueObject;
                     stringValue = string.Format("{0}, {1}, {2}, {3}", color.R, color.G, color.B, color.A);
                     break;
                  }

               case "Rectangle":
                  {
                     Rectangle rectangle = (Rectangle)valueObject;
                     stringValue = string.Format("{0}, {1}, {2}, {3}", rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);
                     break;
                  }

               case "DateTime":
                  {
                     DateTime dateTime = (DateTime)valueObject;
#if WINDOWS
                     stringValue = dateTime.ToBinary().ToString();
#else
                     stringValue = dateTime.Ticks.ToString();
#endif
                     break;
                  }

               case "TimeSpan":
                  {
                     TimeSpan timeSpan = (TimeSpan)valueObject;
                     stringValue = timeSpan.Ticks.ToString();
                     break;
                  }

               default:
                  stringValue = valueObject.ToString();
                  break;
            }
         }

         return stringValue;
      }
}

Related Tutorials