I hope you guys read the previous article of mine. which i mentioned about the Advnance XML serialization mechanisms which you can use in your projects to overcome some recurring problems. so now I'm going to show you some generic methods which you can use to slove XML deserialization related problems. Actually I don't have lot of time to explain more about these functions but don't worry I added header comments and inline comment to explain the functionality of these code segments. If you want to know more please comment or message me. Have a nice day guys... see you soon.
/// <summary>
/// This method will convert (deserialize) XML file to a Object collection
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="document">The document.</param>
/// <param name="rootName">Name of the root.</param>
/// <returns>List of deserialized values from Xml</returns>
public static List<T> DeserializeFromXmlToList<T>(string document, string rootName)
{
try
{
XmlSerializer serializer = string.IsNullOrEmpty(rootName) ? new XmlSerializer(typeof(List<T>)) : new XmlSerializer(typeof(List<T>), new XmlRootAttribute(rootName));
using (StringReader stream = new StringReader(document))
{
XmlTextReader reader = new XmlTextReader(stream);
List<T> resultList = (List<T>)serializer.Deserialize(reader);
return resultList;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// This Method will Deserialize xml to an object
/// </summary>
/// <typeparam name="T">Type of the Object</typeparam>
/// <param name="document">XML file as a string stream</param>
/// <returns>Object with values</returns>
public static T DeserializeFromXml<T>(string document)
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringReader stream = new StringReader(document))
{
XmlTextReader reader = new XmlTextReader(stream);
T result = (T)serializer.Deserialize(reader);
return result;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
Comments
Post a Comment