Code examples for C # XML Serialization classes
Using system;using system.collections.generic;using system.linq;using system.text;using System.IO;using System.Xml; Using system.xml.serialization;using imps.services.commonv4;namespace imps.services.idcservice.utility{public Class Xmlserializerex {private static itracing _tracing = tracingmanager.gettracing ("Xmlserializerex"); <summary>///object converted to XML//</summary>//<typeparam name= "T" ></TYPEPARAM&G T <param name= "obj" ></param>///<returns></returns> public static string SAVEXMLF romobj<t> (T obj) {if (obj = = null) return null; XmlSerializer serializer = new XmlSerializer (typeof (T)); XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces (); namespaces. ADD (String. Empty, String. Empty); MemoryStream stream = new MemoryStream (); XmlTextWriter xtw = new XmlTextWriter (Stream, ENCODING.UTF8); Xtw. formatting = formatting.indented; try {Serializer. Serialize (stream, obj,namespaces); } catch {return null;} Stream. Position = 0; String returnstr = String. Empty; using (StreamReader sr = new StreamReader (stream, Encoding.UTF8)) {String line = ""; while (line = Sr. ReadLine ()) = null) {returnstr + = line; }} return returnstr; } public static T loadobjfromxml<t> (Stream s) {XmlSerializer serializer = new Xmlserialize R (typeof (T)); try {return (T) serializer. Deserialize (s)); } catch {return default (T);} }///<summary>//XML deserialized to object///</summary>//<typeparam name= "T" ></t Ypeparam>//<param name= "Data" ></param>///<returns></returns> public static T LOADOBJFROMXML&L T T> (String data) {using (MemoryStream stream = new MemoryStream ()) {using (StreamWriter SW = new StreamWriter (stream, Encoding.UTF8)) {SW. Write (data); Sw. Flush (); Stream. Seek (0, Seekorigin.begin); return loadobjfromxml<t> (stream); } } } }}
The above is the C # XML serialization Class code example of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!