对象:
[Serializable]
public class User
{
public string ID { get; set; }
public string Name { get; set; }
}
public class User
{
public string ID { get; set; }
public string Name { get; set; }
}
将对象实体序列化成字符串
public static string XMLSerialize<T>(T entity)
{
StringBuilder buffer = new StringBuilder();
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextWriter writer = new StringWriter(buffer))
{
serializer.Serialize(writer, entity);
}
return buffer.ToString();
}
{
StringBuilder buffer = new StringBuilder();
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextWriter writer = new StringWriter(buffer))
{
serializer.Serialize(writer, entity);
}
return buffer.ToString();
}
将字符(XML格式)序列化成实体对象
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;
}
{
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;
}