常用的系列化定義(using system.xml.serialization;)
[xmlattribute("name")] // 定義
[xmlelement("label")] // 定義…
[xmlignoreattribute()] // 跳過系列化
[xmlelement("description", isnullable = false)] // 定義…,在屬性值為null時不顯示該元素,即可選
[xmlarray("temp_var_list", isnullable=false)] // 定義………
,即陣列物件的根結點
[xmlarrayitem("temp_var_item")] // 定義………,即資料元素的根結點,常與xmlarray組合使用
[xmlroot("dpd")] // 定義要結點
幾個注意事項
(1)需序列化的字段必須是公共的(public)
(2)需要序列化的類都必須有乙個無參的建構函式
(3)列舉變數可序列化為字串,無需用[xmlinclude]
(4)匯出非基本型別物件,都必須用[xmlinclude]事先宣告。該規則遞迴作用到子元素
如匯出arraylist物件,若其成員是自定義的,需預包含處理:
using system.xml.serialization;
[xmlinclude(typeof(自定義類))]
(5)attribute中的isnullable引數若等於false,表示若元素為null則不顯示該元素。
也就是說:針對值型別(如結構體)該功能是實效的
若陣列包含了100個空間,填充了10個類物件,則序列化後只顯示10個節點
若陣列包含了100個空間,填充了10個結構體物件,則序列化後會顯示100個節點
(6)真正無法xml序列化的情況
某些類就是無法xml序列化的(即使使用了[xmlinclude])
idictionary(如hashtable)
system.drawing.color
system.drawing.font
securityattribute宣告
父類物件賦予子類物件值的情況
物件間迴圈引用
(7)對於無法xml序列化的物件,可考慮
使用自定義xml序列化(實現ixmlserializable介面)
實現idictionary的類,可考慮①用其它集合類替代;②用類封裝之,並提供add和this函式
某些型別需要先經過轉換,然後才能序列化為 xml。如xml序列化system.drawing.color,可先用toargb()將其轉換為整數
過於複雜的物件用xml序列化不便的話,可考慮用二進位制序列化
例項
[serializableattribute] // 定義本類系列化
[xmlroot("dpd")] // 定義為xml的根結點
public class dataprocessdef
[xmlelement("is_published")] // 列舉型別可以系列化成字串
public publishedtypes ispublished
[xmlelement("data_item")] // 輸出…
public dataitem dataitem
[xmlarray("property_list")] // 組合使用,輸出………
[xmlarrayitem("property_item", isnullable=false)]
public propertyitem propertylist
[xmlelement("custom_item", isnullable=false)] // 輸出………
public customitem customitems
[xmlignoreattribute()] // 不系列化
public string sourcename
另一種方法
namespace testcsxml
[xmlelement("temp")]
public string temp
set}
private string _temp;
}[serializable]
[xmlroot("root")]
[xmlinclude(typeof(subclass))]
public class class1
[xmlelement("test")]
public string test
set}
[xmlattribute("name")]
public string name
set}
[xmlelement("mooo")]
public ilist lst
set}
[xmlelement("subclass")]
public ilist subcls
set}
private string _test;
private string _name;
private ilist _list = new list();
private ilist _listobj = new list();}}
使用方法
private void button5_click(object sender, eventargs e)
XML 物件系列化與反系列化
using system using system.collections.generic using system.web using system.text using system.reflection using system.xml using system.xml.serializati...
系列化與反序列化分析
c 中的 序列化 serializable 理解 我的理解 比如用乙個類描述一張合同,而這個類例項化後其中的字段儲存著合同的資訊,如果現在要把這個類的例項傳送到另一台機器 另乙個窗體或是想儲存這個類以便以 後再取出來用 持久化物件 可以對這個類進行序列化 序列化實際上是乙個資訊流 傳送或儲存,用的時...
C 基礎和規範化系列 2
c 分類有很多種形式,但按照是否包含指標變數對類的影響很大,按照是否包含指標變數來進行分類。需要定義big three 關鍵的3個方法 pragma once include using namespace std class mystring private char m data include...