求问一个可序列化的C#对象,如何转成一个XML格式的文件或字符串
展开全部
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextWriter writer = new StringWriter(buffer)){serializer.Serialize(writer, entity);}
return buffer.ToString();}反序列化:
public static T DeXMLSerialize<T(string xmlString){T cloneObject = default(T);
StringBuilder buffer = new StringBuilder();
buffer.Append(xmlString);
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(buffer.ToString())){Object obj = serializer.Deserialize(reader);
cloneObject = (T)obj;}
return cloneObject;}方法二:/// <summary
/// 对象序列化成 XML String
/// </summary
public static string XmlSerialize<T(T obj){string xmlString = string.Empty;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream()){xmlSerializer.Serialize(ms, obj);
xmlString = Encoding.UTF8.GetString(ms.ToArray());}return xmlString;}
/// <summary
/// XML String 反序列化成对象
/// </summary
using (TextWriter writer = new StringWriter(buffer)){serializer.Serialize(writer, entity);}
return buffer.ToString();}反序列化:
public static T DeXMLSerialize<T(string xmlString){T cloneObject = default(T);
StringBuilder buffer = new StringBuilder();
buffer.Append(xmlString);
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(buffer.ToString())){Object obj = serializer.Deserialize(reader);
cloneObject = (T)obj;}
return cloneObject;}方法二:/// <summary
/// 对象序列化成 XML String
/// </summary
public static string XmlSerialize<T(T obj){string xmlString = string.Empty;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream()){xmlSerializer.Serialize(ms, obj);
xmlString = Encoding.UTF8.GetString(ms.ToArray());}return xmlString;}
/// <summary
/// XML String 反序列化成对象
/// </summary
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询