Click here to Skip to main content
15,894,825 members
Articles / Programming Languages / XML

Serialize/Deserialize any object to an XML file

Rate me:
Please Sign up or sign in to vote.
4.88/5 (11 votes)
28 May 2013CPOL1 min read 76.3K   3.2K   38  
Code to serialize/deserialize any object to an XML file.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

namespace XmlSerializer
{
    /// <summary>
    /// This class make deal with PropertyInfo or FieldInfo as the same way
    /// </summary>
    public class MemberInfox
    {
        private MemberInfo Member;
        public Type ObjectType, ValueType, MemberType;
        /// <summary>
        /// Gets the object instance that contains this property
        /// </summary>
        public object ProbertyObject;
        public string Name;
        public bool MemberExists { get { return Member != null; } }
        public bool CanRead, CanWrite;
        public MemberInfox(object ProbertyObject, string Name, bool SearchForPriviteFieldInCasePublicFieldIsReadOnly=true)
        {
            this.ProbertyObject = ProbertyObject;
            this.Name = Name;
            this.ObjectType =ProbertyObject==null?null: ProbertyObject.GetType();
            Member = Utility.GetMemberInfo(ObjectType, Name, SearchForPriviteFieldInCasePublicFieldIsReadOnly);
            if (Member is PropertyInfo)
            {
                MemberType = (Member as PropertyInfo).PropertyType;
                CanRead = (Member as PropertyInfo).GetGetMethod(true) != null;
                CanWrite = (Member as PropertyInfo).GetSetMethod(true) != null;
            }
            else if (Member is FieldInfo)
            {
                MemberType = (Member as FieldInfo).FieldType;
                CanRead = CanWrite = true;
            }
            else return;

            var val = GetValue();
            if (val != null)
                ValueType = val.GetType();
            else ValueType = MemberType;
        }

        /// <summary>
        /// Gets the runtime current value of this property of field
        /// </summary>
        /// <returns></returns>
        public object GetValue()
        {
            if (!CanRead)
                return null;
            try
            {
                if (Member is PropertyInfo)
                    return (Member as PropertyInfo).GetValue(ProbertyObject, null);
                else if (Member is FieldInfo)
                    return (Member as FieldInfo).GetValue(ProbertyObject);
            }
            catch { }
            return null;
        }
        /// <summary>
        /// Sets the runtime current value of this property of field
        /// </summary>
        public bool SetValue(object value)
        {
            try
            {
                if (!CanWrite||!MemberExists)
                    return false;
                if (value == null && MemberType.IsValueType)
                    return false;
                if (MemberType.IsEnum)
                {
                    if (!Enum.IsDefined(MemberType, value + ""))
                        return false;
                    else if (value != null && value.GetType() != MemberType)
                        value = Enum.Parse(MemberType, value + "");
                }
                if (value != null && !MemberType.IsAssignableFrom(value.GetType()))
                    return false;
                if (Member is PropertyInfo)
                    (Member as PropertyInfo).SetValue(ProbertyObject, value, null);
                else if (Member is FieldInfo)
                    (Member as FieldInfo).SetValue(ProbertyObject, value);
                return true;
            }
            catch { return false; }
        }
        private Dictionary<string, object> customAttributes;
        
        /// <summary>
        /// Gets the runtime current value of this property of field
        /// </summary>
        /// <returns></returns>
        public object GetCustomAttributes(Type attributeType)
        {
            string key = attributeType.FullName;
            if (customAttributes == null) 
                customAttributes = new Dictionary<string, object>();
            if (!customAttributes.ContainsKey(key))
            {
                object[] a;
                try { a = Member.GetCustomAttributes(attributeType, true); }
                catch { a = null; }
                if (a == null || a.Length == 0) customAttributes[key] = null;
                else customAttributes[key] = a[0];
            }
            return customAttributes[key];
        }

        public override string ToString()
        {
            return Name;
        }
        public static List<MemberInfox> GetMemberInfox(object obj, bool SearchForPriviteFieldInCasePublicFieldIsReadOnly = true,bool ReturnOnlyChangedProperties=true)
        {
            List<MemberInfox> members = new List<MemberInfox>();
            if (obj == null) return members;
            var type = obj.GetType();
            while (type!=null&& type != typeof(object))
            {
                foreach (PropertyDescriptor prop in Utility.GetPropertyDescriptors(type))
                {
                    try
                    {
                        if (ReturnOnlyChangedProperties && !prop.ShouldSerializeValue(obj)) continue;
                        if (members.Exists(m => m.Name == prop.Name)) continue;
                        members.Add(new MemberInfox(obj, prop.Name, SearchForPriviteFieldInCasePublicFieldIsReadOnly));
                    }
                    catch { }
                }
                type = type.BaseType;
            }
            return members;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Desktop Team
Palestinian Territory (Occupied) Palestinian Territory (Occupied)
I have advanced skills in desktop apps development, i have built many apps for many corporations.

i'm using the follow languages in my work:
1- C# Language.
2- VB6 Language.
3- Asp.net using C#.
4- Crystal Reports.

i have more than 7 experience years in coding and programming.

Systems and apps Developed by Us:
1-E-Archive System (VB6,Supports multi DataBase Engins).
2-SMS System (Multi languages such VB6,C#,Asp.Net and Gizmox).
3-Multi Camera Monitor System-Motion Detection and record(C#).
4-Administrative Evaluation System (Asp.net).
5-E-Clinic System (C#-using my business layer generator,Supports multi DataBase Engines).
6-Data Access Layer Generator Framework(C#).
7-Sip Provider -VOIP- Softphone (C#- for Italian company).
8-Training course Manager System(C#-for UCAS).
9-Computer Exam System (VB6,Oracle DataBase).
10-Dialer System (VB6).
11-Implement Google API using C# (Translation and web Search).
12-Print Management Enterprise(C#)
13-Elections System (C#- using my business layer generator).
14-Advanced English competition (VB6).
15-Remote USB Sharing (C/C++,VB6).
16-Watch Attendance (C/C++,VB6).
17-Tube Spy (C#).
18-AdminYourTube (C#)
19- Transport Reservation System (C#,Asp.net,Ajax,Jquery)

Please visit my elance URL http://ashrafnet.elance.com

Comments and Discussions