CSharp examples for System.Xml:XML Serialization
Deserializes an XML string to an instance of T.
// This program is free software; you can redistribute it and/or using System.Xml.Serialization; using System.IO;// w ww . ja v a 2 s .co m using System.Globalization; using System.Diagnostics.CodeAnalysis; using System; public class Main{ #endregion #region static FromXml method /// <summary> /// Deserializes an XML string to an instance of T. /// TODO: check the XML against a schema for the type and report any errors /// </summary> /// <param name="xml"> /// An XML string representing an instance of the supplied System.Type. /// </param> /// <returns> /// The System.Object represented by the supplied XML string. /// </returns> /// <exception cref="InvalidDataException"> /// The XML string could not be deserialized to the given type. See the /// InnerException for more information. /// </exception> /// <exception cref="ArgumentNullException"> /// The supplied System.Type is null. /// </exception> [SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T FromXml( string xml ) { try { XmlSerializer xs = new XmlSerializer( typeof( T ) ); TextReader tr = new StringReader( xml ); return (T) xs.Deserialize( tr ); } catch( InvalidOperationException ex ) { #region handle the exception string message = "XmlDeserializer.FromXmlString was unable to " + "deserialize an XML string to an instance of the type " + typeof( T ).ToString() + ". " + Environment.NewLine + Environment.NewLine + "This could mean the XML string is corrupt, or it could mean " + "you are trying to deserialize an XML string which is a " + "representation of a completely different System.Type." + Environment.NewLine + Environment.NewLine + "The XML string is: " + xml; throw new InvalidDataException( message, ex ); #endregion } } }