Tuesday, October 7, 2014

From & To XML

 public class CustomSerializer<T>
{
        public string ToXml(T obj)
        {
            return ToXml(obj, new Type[] { });
        }

        public string ToXml(T obj, Type[] extraTypes)
        {
            string output = string.Empty;

            using (StringWriter writer = new StringWriter())
            {
                XmlSerializer serializer = null;

                // Serialize the entity.
                serializer = new XmlSerializer(typeof(T), extraTypes);
                serializer.Serialize(writer, obj);

                // Get serialized string.
                output = writer.ToString();
                writer.Close();

                return output;
            }
        }

        public T FromXml(string xmlString)
        {
            return FromXml(xmlString, new Type[] { });
        }

        public T FromXml(string xmlString, Type[] extraTypes)
        {
            T result = default(T);
            XmlSerializer serializer = null;

            using (StringReader reader = new StringReader(xmlString))
            {
                // Deserialize the entity.
                serializer = new XmlSerializer(typeof(T), extraTypes);
                result = (T)serializer.Deserialize(reader);
            }
            return result;
        }

}

No comments:

Post a Comment