Friday, February 7, 2014

Common .Net Library Methods: Easy XML Serialization and deserialization

Serializing XML to an object of a given type and back has been very common in a lot of my projects. It may not be allowable when you are working on multiple projects in different groups to import a common class library so I thought I'd post some basic serialization code generic to most projects that I have had to use a lot lately.
        /// <summary>
        /// Deserializes an XML document into a given type.
        /// </summary>
        /// <typeparam name="T">The type to deserialize.</typeparam>
        /// <param name="xml"> The xml. </param>
        /// <returns> An object representative of the XML document. </returns>
        public T Deserialize<T>(string xml)
            var xmlSerializer = new XmlSerializer(typeof(T));
            using (var reader = XmlReader.Create(new StringReader(xml)))
                if (xmlSerializer.CanDeserialize(reader))
                    return (T)xmlSerializer.Deserialize(reader);

            return default(T);

/// <summary> /// Serializes an object into an XML document. /// </summary> /// <param name="path"> The path. </param> /// <param name="o"> The object to serialize. </param> public void Serialize(string path, object o) { using (var writer = new StreamWriter(path)) { new XmlSerializer(o.GetType()).Serialize(writer, o); } }

No comments:

Post a Comment