asp.net xml序列化與反序列化
更新時間:2008年08月13日 10:44:41 作者:
在.NET下有一種技術叫做對象序列化,它可以將對象序列化為二進制文件、XML文件、SOAP文件,這樣, 使用經過序列化的流進行傳輸效率就得到了大大的提升。
反序列化就是讀取xml文件并將其值自動匹配給類中的公有屬性或方法或字段,也就是上面的逆操作。 C#復制代碼
webinfo info = new webinfo();
//用webinfo這個類造一個XmlSerializer
XmlSerializer ser = new XmlSerializer(typeof(webinfo));
string path = Server.MapPath("webinfo.xml");
//Stream用于提供字節(jié)序列的一般視圖,這里將打開一個xml文件
Stream file = new FileStream(path, FileMode.Open, FileAccess.Read);
//把字節(jié)序列(stream)反序列化
info = (webinfo)ser.Deserialize(file);
Response.Write("站長:" + info.userName + "<br>");
Response.Write("站名:" + info.webName + "<br>");
Response.Write("域名:" + info.webUrl);
輸出結果:
為了更好的封裝和保護類的成員和方法,我們將類webinfo改寫成: 折疊展開C#復制代碼
public class webinfo
{
//站長
private string userName;
public string UserName
{
get
{
return userName;
}
set
{
userName = value;
}
}
//站名
private string webName;
public string WebName
{
get
{
return webName;
}
set
{
webName = value;
}
}
//域名
private string webUrl;
public string WebUrl
{
get
{
return webUrl;
}
set
{
webUrl = value;
}
}
}
使用時區(qū)別僅僅是小小的改動具體的可以看下面: C#復制代碼
webinfo info = new webinfo();
info.userName = "腳本之家";-->info.UserName = "腳本之家";
info.webName = "腳本"; -->info.WebName = "腳本";
info.webUrl = "http://www.dhdzp.com"; -->//自己寫吧
相關文章
asp.net下使用Request.From獲取非服務器控件的值的方法
asp.net下使用Request.From獲取非服務器控件的值的方法,需要的朋友可以參考下。2010-03-03
數據庫SqlParameter 的插入操作,防止sql注入的實現代碼
今天學習了一下SqlParameter的用法,原來這么寫是為了防止sql注入,破壞數據庫的。并自己動手連接了數據庫。2013-04-04

