C# Example: Read/Write XML File

 

(Serializing/Deserializing)

Read or DeSerializing XML File

        /// <summary>
        /// Reads XML config file.
        /// </summary>
        /// <typeparam name="T">Class to read into.</typeparam>
        /// <param name="xmlFile">XML file location.</param>
        /// <param name="type">Class type to read from.</param>
        /// <returns></returns>
        public static T ReadXMLFile<T>(string xmlFile, Type type)
        {
            if (!File.Exists(xmlFile))
            {
                log.FatalFormat("XML config file '{0}' not found!", xmlFile);
                return default(T);
            }
 
            log.InfoFormat("Found XML config file '{0}'. Deserializing...", xmlFile);
            var reader = new System.Xml.Serialization.XmlSerializer(type);
            var xmlfile = new System.IO.StreamReader(xmlFile);
            return (T)reader.Deserialize(xmlfile);
        }

* Example usage:

        [TestMethod]
        public void TestReadXMLFile()
        {
            UserMenu um = Util.ReadXMLFile<UserMenu>(
                Properties.MyMenuXMLFile, typeof(UserMenu));
            Assert.IsNotNull(um);
            log.InfoFormat("Got MyMenu: {0}.", um.MenuName);
        }

Write or Serializing XML File

        /// <summary>
        /// Generate a dummy menu XML file.
        /// </summary>
        /// <param name="xmlFile">Output XML file name.</param>
        /// <param name="type">Coresponding class.</param>
        /// <param name="force">If true, overwrite existing XML file.</param>
        public static void GenerateDummyXMLFile(string xmlFile, Type type, bool force)
        {
            if (File.Exists(xmlFile) && !force)
            {
                log.WarnFormat(
                    "XML config file '{0}' exists and we're not forcing the serialization.", xmlFile);
                return;
            }
 
            log.InfoFormat("XML config file '{0}' not found. Serializing...", xmlFile);
            var writer = new System.Xml.Serialization.XmlSerializer(type);
            var xmlfile = new System.IO.StreamWriter(xmlFile);
            writer.Serialize(xmlfile, Properties.DummyMyMenu);
            xmlfile.Close();
            log.InfoFormat("Serialized to xml file '{0}'.", xmlFile);
        }

* Example usage:

        [TestMethod]
        public void TestGenerateDummyXML()
        {
            Util.GenerateDummyXMLFile(Properties.MyMenuXMLFile, typeof(UserMenu), false);
        }
This entry was posted in c# and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

This site uses Akismet to reduce spam. Learn how your comment data is processed.