XMLserializer example

It can be useful to serialize lists of Entity's to XML. In my case, for instance, the list with entity's are send to a Biztalk-server which is going to process it.

Example: serialize List<> to XML:

            XmlSerializer serializer = new XmlSerializer(List.GetType());
            FileStream fstream = new FileStream(@locatie, FileMode.Create, FileAccess.Write, FileShare.None);
            serializer.Serialize(fstream, List);
            fstream.Close();

Deserializing the XML is allso easily done with the XMLserialzer class:
Example:

            List <CentraalArtikelBestand> result = new List();
            XmlSerializer serializer = new XmlSerializer(result.GetType());
            using (XmlReader xmlReader = XmlReader.Create(location))
            {
                result = (List<CentraalArtikelBestand> )serializer.Deserialize(xmlReader);
            }
            return result;

Because you want to serialize all kind of ojbect and don't want to build a method for every object to be serialized, it's a better idea to make a generic approach:

Example:

///
    /// Base Object for reading and writing XML
    ///
    public class XMLbase
    {
        ///
        /// Writes an object to an XML file
        ///
        ///Object type
        ///The object to serialize
        ///The fysic location
        ///
        public virtual ReturnMessage WriteXML(T xmlObject, string location, string filename)
        {
            // validation
            if (xmlObject == null)
            {
                return ReturnMessage.GetReturnMessage(false, "Object to serialize cannot be null!", null);
            }
            if (string.IsNullOrEmpty(location))
            {
                return ReturnMessage.GetReturnMessage(false, "Location for writing XML cannot be empty!", null);
            }
            if (string.IsNullOrEmpty(filename))
            {
                return ReturnMessage.GetReturnMessage(false, "Name off the file for writing XML cannot be empty!", null);
            }

            // create filePath
            string fullPath = Path.Combine(location, filename);
            // serialize
            try
            {
                var serializer = new XmlSerializer(typeof(T));
                using (var fstream = new FileStream(fullPath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    serializer.Serialize(fstream, xmlObject);
                }
            }
            catch (Exception excp)
            {
                return ReturnMessage.GetReturnMessage(false, string.Format("Error writing xml: {0}", excp.Message), excp);
            }

            return ReturnMessage.GetReturnMessage(true, string.Format("Object: {0} is serialized to xml-file{1}", xmlObject.GetType().Name, location), null);

        }

        ///
        /// Validates the XML file
        ///
        ///
        ///
        public virtual ReturnMessage Validate(string location, string filename)
        {
            // validation
            if (string.IsNullOrEmpty(location)) { return ReturnMessage.GetReturnMessage(false, "Location for loading XML cannot be empty", null); };
            if (string.IsNullOrEmpty(filename)) { return ReturnMessage.GetReturnMessage(false, "file name for loading XML cannot be empty", null); };

            string fullPath = Path.Combine(location, filename);
            if (!File.Exists(fullPath)) { return ReturnMessage.GetReturnMessage(false, "The file in the specified location does not exist!", null); };
            
            var serializer = new XmlSerializer(typeof(T));
            using (var xmlReader = XmlReader.Create(fullPath))
            {
                bool succeeded = serializer.CanDeserialize(xmlReader);
                return ReturnMessage.GetReturnMessage(succeeded,string.Empty, null);
            }
        }

        ///
        /// Returns an object created from
        /// a XmlFile
        ///
        ///The location off the XML File
        /// 
        public virtual T GetFromXml(string location, string filename)
        {
            // validation
            if (string.IsNullOrEmpty(location)) { throw new ArgumentNullException("Location for loading XML cannot be empty"); };

            string fullPath = Path.Combine(location, filename);
            if (!File.Exists(fullPath)) { throw new ArgumentNullException("The file in the specified location does not exist!"); };

            var serializer = new XmlSerializer(typeof(T));
            using (var xmlReader = XmlReader.Create(fullPath))
            {
                var result = (T)serializer.Deserialize(xmlReader);
                return result;
            }
        }
    }

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!