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> /// 对象转换成xml /// </summary> /// <typeparam name="t"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string savexmlfromobj<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 xmlserializer(typeof(t)); try { return ((t)serializer.deserialize(s)); } catch { return default(t); } } /// <summary> /// xml反序列化到对象 /// </summary> /// <typeparam name="t"></typeparam> /// <param name="data"></param> /// <returns></returns> public static t loadobjfromxml<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); } } } } }
以上就是c# xml序列化类的代码实例详解的内容。
