序列化与反序列化
建立Man.cs
using System.Xml.Serialization;
///<summary>
///Man 的摘要说明
///</summary>
[Serializable]
public class Man
{
public Man() {
}
[XmlElement("Man_Age")]
public int Age
{
get;
set;
}
public string Name
{
get;
set;
}
public string tel
{
get;
set;
}
public Man(int Age, string Name ,string tel)
{
this.Age = Age;
this.Name = Name;
this.tel = tel;
}
public string Show()
{
return String.Format(" Name : {0} Age: {1} tel :{2}", this.Name, this.Age,this.tel);
}
public void AddData(int Age, string Name, string tel)
{
this.Age = Age;
this.Name = Name;
this.tel = tel;
}
}
1.二进制格式序列化
首先引入
using System.Runtime.Serialization.Formatters.Binary;
然后通过
string Path = "C:\\man.text";
Man m=new Man (18,"小王1","18618618618");
FileStream fs = new FileStream(Path, FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs,m);
fs.Close();
二进制序列化反序列化
string Path = "C:\\man.text";
Man m = null;
FileStream fs = new FileStream(Path,FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
m = formatter.Deserialize(fs) as Man ;//
fs.Close();
return m.Show();
2.XML序列化
string Path = "C:\\man.xml";
Man m = new Man();
m.AddData(18, "小王333", "18618618618");
using (StreamWriter fs = new StreamWriter (Path))
{
XmlSerializer xmlSerializer = new XmlSerializer(m.GetType());
xmlSerializer.Serialize(fs, m);
}
xml反序列化
string Path = "C:\\man.xml";
Man m = new Man ();
FileStream fs = new FileStream(Path,FileMode.Open);
XmlSerializer xmlSerializer = new XmlSerializer(m.GetType());
m = xmlSerializer.Deserialize(fs) as Man ;//
fs.Close();
return m.Show();
插曲: 可以通过 [NonSerialized] 对对象中的的部分数据取消序列化 做到部分暴露
如果声明一个类 而没有共有字段 那么这个类进行xml序列化的时候 将无法把数据写入xml文件
public class XMLserializeHelp { public static void Serialize<T>(string path, T t) where T:class { using (StreamWriter sw = new StreamWriter(path)) { XmlSerializer xml = new XmlSerializer(t.GetType()); xml.Serialize(sw, t); } } public static T Deserialize<T>(string path) where T:class { T t = default(T); FileStream fs = new FileStream(path, FileMode.Open); XmlSerializer xmlSerializer = new XmlSerializer(t.GetType()); t = xmlSerializer.Deserialize(fs) as T; fs.Close(); return t; } }
反序列化输出XML:
反序列化基类:
public class BaseApi : System.Web.UI.Page { /// <summary> /// 反序列化 /// </summary> /// <param name="type"></param> /// <param name="xml"></param> /// <returns></returns> public static object Deserialize(Type type,string strXml) { using (StringReader sr = new StringReader(strXml)) { XmlSerializer xmldes = new XmlSerializer(type); return xmldes.Deserialize(sr) ; } } /// <summary> /// 序列化 /// </summary> /// <param name="type">类型</param> /// <param name="obj">对象</param> /// <returns></returns> public static string Serializer(object obj,Type type) { MemoryStream Stream = new MemoryStream(); XmlSerializer xml = new XmlSerializer(type); try { //序列化对象 xml.Serialize(Stream, obj); } catch (InvalidOperationException) { throw; } Stream.Position = 0; StreamReader sr = new StreamReader(Stream); string str = sr.ReadToEnd(); sr.Dispose(); Stream.Dispose(); return str; } }
定义 输出XML格式对象,同时指定字段 输出 <![CDATA[ ]]> 格式
[Serializable] public class News { public News() { } public int id { get; set; } public string title { get; set; } [XmlIgnore] public string content { get; set; } [XmlElement("text_content")] public XmlNode text_content { get { return new XmlDocument().CreateCDataSection(this.content); } set { this.content = value.Value; } } }
输出:
public partial class news_api : BaseApi { protected void Page_Load(object sender, EventArgs e) { string method = Request.QueryString["method"]; switch (method) { case "get_content": get_content(int.Parse(Request.QueryString["id"])); break; } } public void get_content(int id) { News model = new News(); model.content = "rhythmk"; model.id = id; model.title = "测试XML "; Response.ContentType = "text/xml"; Response.Write(Serializer(model,typeof(News))); Response.End(); } }
备注:
调整了基类方法写法:
/// <summary> /// 反序列化 /// </summary> /// <param name="type"></param> /// <param name="xml"></param> /// <returns></returns> public static T Deserialize<T>(string strXml) where T:class { using (StringReader sr = new StringReader(strXml)) { XmlSerializer xmldes = new XmlSerializer(typeof(T)); return xmldes.Deserialize(sr) as T; } } /// <summary> /// 序列化 /// </summary> /// <param name="type">类型</param> /// <param name="obj">对象</param> /// <returns></returns> public static string Serializer<T>(object obj) { T t = (T)obj; MemoryStream Stream = new MemoryStream(); XmlSerializer xml = new XmlSerializer(t.GetType()); try { //序列化对象 xml.Serialize(Stream, obj); } catch (InvalidOperationException) { throw; } Stream.Position = 0; StreamReader sr = new StreamReader(Stream); string str = sr.ReadToEnd(); sr.Dispose(); Stream.Dispose(); return str; }