asp.net xml序列化與反序列化第1/2頁
2024-07-10 13:21:51
供稿:網友
在網上找了一些關于xml序列化與反序列化的資料,摘錄下:
在.NET下有一種技術叫做對象序列化,它可以將對象序列化為二進制文件、XML文件、SOAP文件,這樣, 使用經過序列化的流進行傳輸效率就得到了大大的提升。
在.NET中提供了兩種序列化:二進制序列化、XML和SOAP序列化。對于WEB應用來說,用得最多的是第二種———XML和SOAP序列化。
XML 序列化將對象的公共字段和屬性或者方法的參數和返回值轉換(序列化)為符合特定 XML 架構定義 語言 (XSD) 文檔的 XML 流。
XML 序列化生成強類型的類,并為存儲或傳輸目的將其公共屬性和字段轉換為序列格式(在此情況下為
XML)。
注意:
1、XML 序列化不轉換方法、索引器、私有字段或只讀屬性(只讀集合除外)。
2、使用Serialize和Deserialize需要指明命令空間System.Xml.Serialization,using System.IO。
xml序列化簡單的應用舉例:
有個類定義為:
C#復制代碼
public class webinfo
{
public string userName;
public string webName;
public string webUrl;
}
那么通過序列化我們可以將其序列化為: XML/HTML復制代碼
<?xml version="1.0"?>
<webinfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<userName>武林網</userName>
<webName>腳本</webName>
<webUrl></webUrl>
</webinfo>
主要的代碼如下: C#復制代碼
webinfo info = new webinfo();
info.userName = "武林網";
info.webName = "腳本";
info.webUrl = "http://www.49028c.com";
//用webinfo這個類造一個XmlSerializer
XmlSerializer ser = new XmlSerializer(typeof(webinfo));
//xml保存路徑,序列化成功后可以通過查看該文件看到序列化后結果
string path = Server.MapPath("webinfo.xml");
try
{
//Stream用于提供字節序列的一般視圖,這里將在根目錄下建立一個xml文件
Stream file = new FileStream(path, FileMode.Create, FileAccess.Write);
//把Stream對象和info一起傳入,序列化出一個XML文件,如果沒這一步,建立的xml內容為空
ser.Serialize(file, info);
//釋放資源
file.Close();
file.Dispose();
Response.Write("序列化成功");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
}
反序列化就是讀取xml文件并將其值自動匹配給類中的公有屬性或方法或字段,也就是上面的逆操作。 C#復制代碼
webinfo info = new webinfo();
//用webinfo這個類造一個XmlSerializer
XmlSerializer ser = new XmlSerializer(typeof(webinfo));
string path = Server.MapPath("webinfo.xml");
//Stream用于提供字節序列的一般視圖,這里將打開一個xml文件
Stream file = new FileStream(path, FileMode.Open, FileAccess.Read);
//把字節序列(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;
}
}
}
使用時區別僅僅是小小的改動具體的可以看下面: C#復制代碼
webinfo info = new webinfo();
info.userName = "武林網";-->info.UserName = "武林網";
info.webName = "腳本"; -->info.WebName = "腳本";
info.webUrl = "http://www.49028c.com"; -->//自己寫吧