CSharp examples for System.Xml:XML Serialization
Deserializes the specified object XML.
using System.Xml.Serialization; using System.Xml; using System.Text; using System.IO;//from ww w.j av a 2 s . co m using System.Collections.Generic; using System; public class Main{ /// <summary> /// Desirializes the specified object XML. /// </summary> /// <param name="objectXml">The object XML.</param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public static T Deserialize<T>(string objectXml) { XmlSerializer serializer = new XmlSerializer(typeof(T)); serializer.UnknownAttribute += new XmlAttributeEventHandler(OnSerializerUnknownAttribute); serializer.UnknownElement += new XmlElementEventHandler(OnSerializerUnknownElement); serializer.UnknownNode += new XmlNodeEventHandler(OnSerializerUnknownNode); serializer.UnreferencedObject += new UnreferencedObjectEventHandler(OnSerializerUnreferencedObject); MemoryStream memStream = new MemoryStream(); StreamWriter streamWriter = new StreamWriter(memStream, System.Text.Encoding.UTF8); streamWriter.Write(objectXml); //memStream.Flush(); streamWriter.Flush(); memStream.Position = 0; XmlReaderSettings settings = new XmlReaderSettings(); settings.CheckCharacters = false; settings.CloseInput = false; settings.ConformanceLevel = ConformanceLevel.Fragment; settings.IgnoreComments = true; settings.IgnoreWhitespace = true; settings.ValidationType = ValidationType.None; settings.ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags.None; settings.IgnoreProcessingInstructions = true; XmlReader reader = XmlReader.Create(memStream, settings); T result = (T)serializer.Deserialize(reader); reader.Close(); streamWriter.Close(); memStream.Close(); return result; } }