Thursday, March 17, 2011

How to do XML Serialization for entities

I am going to write some helper functions to use for serialization.
This function can serialize and deserialize an entity or List of entities and you can specify how you need to serialize your entity, if the properties should be ax XML element or they should be attributes and also the root name can be set.
using System.Xml;
using System.Xml.Serialization; 

public static class Utility
        public static string SerializeXML<T>(T obj, bool isObjPropAsElement, string rootElementName, 
                                       bool indentElements, bool omitXmlDeclaration, Type[] extraTypes)
            string val = null;
            if (obj != null)
                XmlWriterSettings xwSettings = new XmlWriterSettings();
                if (indentElements)
                    xwSettings.NewLineChars = Environment.NewLine;
                    xwSettings.Indent = true;
                    xwSettings.NewLineOnAttributes = true;

                xwSettings.OmitXmlDeclaration = omitXmlDeclaration;
                xwSettings.Encoding = System.Text.Encoding.UTF8;

                System.IO.MemoryStream memStream = new System.IO.MemoryStream();
                using (XmlWriter writer = XmlWriter.Create(memStream, xwSettings))
                    XmlSerializer xmlSer = GetSerializer<T>(isObjPropAsElement, rootElementName, extraTypes);
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                    ns.Add("", "");
                    xmlSer.Serialize(writer, obj, ns);
                val = new System.Text.UTF8Encoding().GetString(memStream.ToArray());
            return val;
        public static T DeserializeXML<T>(string str, bool isObjPropAsElement, string rootElementName, Type[] extraTypes)
            XmlSerializer xmlSer = GetSerializer<T>(isObjPropAsElement, rootElementName, extraTypes);
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] bytes = encoding.GetBytes(str);
            System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes);
            Object obj = xmlSer.Deserialize(memStream);
            return (T)Convert.ChangeType(obj, typeof(T));
        private static XmlSerializer GetSerializer<T>(bool isObjPropAsElement, string rootElementName, Type[] extraTypes)
            if (extraTypes == null) extraTypes = new Type[] { };

            XmlAttributeOverrides overrides = null;
            if (!isObjPropAsElement)
                overrides = new XmlAttributeOverrides();
                Type type = typeof(T);
                if (type.IsGenericType && type.Name.Equals(typeof(List<>).Name))
                    type = type.GetGenericArguments()[0];

                System.Reflection.PropertyInfo[] props = type.GetProperties();
                foreach (System.Reflection.PropertyInfo prop in props)
                    XmlAttributes attrs = new XmlAttributes();
                    attrs.XmlAttribute = new XmlAttributeAttribute();
                    overrides.Add(type, prop.Name, attrs);
            XmlRootAttribute xmlRootAtt = new XmlRootAttribute();
            xmlRootAtt.ElementName = rootElementName;
            xmlRootAtt.Namespace = "";

            XmlSerializer xmlSer = new XmlSerializer(typeof(T), overrides, extraTypes, xmlRootAtt, "");
            return xmlSer;

To prepare DateTime on .Net side before serializing to XML so that it can be parsed on SQL Server side using XQuery, we can use this function.
private DateTime PrepareDateTimeForSerialization(DateTime d)
    return new DateTime(d.Ticks / 10000 * 10000, DateTimeKind.Utc);


Mike said...

I was searching for an efficient way to do xml serialization.I read the article that you also mentioned but really an example is always an help which you provided neatly.
digital certificates

Post a Comment