1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Text;4 usingSystem.Xml.Serialization;5 usingSystem.IO;6 usingSystem.Xml;7 8 namespaceCommon9 {Ten Public classxmlutility One { A /// <summary> - ///serializing a custom object to an XML string - /// </summary> the /// <param name= "MyObject" >Custom Object Entities</param> - /// <returns>Serialized XML string</returns> - Public Static stringSerializetoxml<t>(T myObject) - { + if(MyObject! =NULL) - { +XmlSerializer xs =NewXmlSerializer (typeof(T)); A atMemoryStream stream =NewMemoryStream (); -XmlTextWriter writer =NewXmlTextWriter (Stream, Encoding.UTF8); -Writer. formatting = Formatting.none;//Indent in - XS. Serialize (writer, myObject); - -Stream. Position =0; inStringBuilder SB =NewStringBuilder (); - using(StreamReader reader =NewStreamReader (Stream, Encoding.UTF8)) to { + stringLine ; - while(line = reader.) ReadLine ())! =NULL) the { * sb. Append (line); $ }Panax Notoginseng Reader. Close (); - } the writer. Close (); + returnsb. ToString (); A } the return string. Empty; + } - $ /// <summary> $ ///deserializing an XML string into an object - /// </summary> - /// <typeparam name= "T" >Object Type</typeparam> the /// <param name= "xml" >XML Characters</param> - /// <returns></returns>Wuyi Public StaticT deserializetoobject<t> (stringXML) the { - T MyObject; WuXmlSerializer serializer =NewXmlSerializer (typeof(T)); -StringReader reader =NewStringReader (XML); AboutMyObject =(T) serializer. Deserialize (reader); $ Reader. Close (); - returnMyObject; - } - } A}
C # XML and objects convert to each other