Using system;using system.collections.generic;using system.linq;using system.text;using System.runtime.serialization;using system.io;using system.xml;namespace common.utility.xmlserialization{//< summary>//DataContractSerializer//</summary>//<typeparam name= "T" ></typeparam> p Ublic class Datacontractserializer<t> {//<summary>//entity serialized as XML string///</SU mmary>//<param name= "meta" ></param>///<returns></returns> public stat IC string toxmlstring (t meta) {DataContractSerializer DCS = new DataContractSerializer (typeof (T)); String xmlstr = String. Empty; using (MemoryStream ms = new MemoryStream ()) {try {DCs. WriteObject (MS, Meta); Xmlstr = Encoding.UTF8.GetString (ms. ToArray ()); Ms. Close (); } catch {throw; }} return xmlstr; }///<summary>//DataContract serialization///</summary>/<param name= "value" >& lt;/param>//<param name= "KnownTypes" > collection of known Types </param>//<returns></returns> public static string Toxmlstring (object value, ienumerable<type> knownTypes = null) {try {DataContractSerializer DataContractSerializer = new DataContractSerializer (value. GetType (), knownTypes); using (MemoryStream ms = new MemoryStream ()) {Datacontractserializer.writeobject (MS, VA Lue); Ms. Seek (0, Seekorigin.begin); using (StreamReader sr = new StreamReader (ms)) {return Sr. ReadToEnd (); } } } catch {throw; }}////<summary> Entity deserialization///</summary>//<param name= "xml" >< ;/param>//<returns></returns> public static T Readfromxml (string xmlstr) { T Meta; try {DataContractSerializer DCs = new DataContractSerializer (typeof (T)); using (TextReader reader = new StringReader (XMLSTR)) {using (XmlReader Xreader = Xmlrea Der. Create (reader)) {meta = (T) DCs. ReadObject (Xreader); }}} catch {throw; } return meta; }///<summary> Entity deserialization///</summary>//<param name= "Xmlstr" ></para m>//<param name= "KnownTypes" >IEnumerable<Type></param>//<returns></returns> public static T Readfromxml (string xmlstr, ienumerable< ; Type> knownTypes = null) {T meta; try {DataContractSerializer DCs = new DataContractSerializer (typeof (T), knownTypes); using (TextReader reader = new StringReader (XMLSTR)) {using (XmlReader Xreader = Xmlreader.create (reader)) {meta = (T) DCs. ReadObject (Xreader); }}} catch {throw; } return meta; } }}
The above is the C # entity class serialization and deserialization two (DataContractSerializer) content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!