2010-01-15 53 views
0

我正在編寫一個程序,該程序基本上會爲本地計算機SAM存儲中的用戶提供大部分內容的xml副本。XMLSerializer不寫入列表中的元素

目前它只爲每個用戶打印一個XMLElement,但不打印它們的屬性。

<?xml version="1.0" encoding="utf-8"?> 
<WindowsUserList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <windowsUserEntry /> 
    <windowsUserEntry /> 
    ... 
    <windowsUserEntry /> 
    <windowsUserEntry /> 
</WindowsUserList> 

這是我的主要代碼,該複選框文本已用於搜索作爲其文本格式的名稱(會計*例如讓用戶accounting1,2,3等..)

windowsUserList listUsers = new windowsUserList(); 
PrincipalContext context = new PrincipalContext(ContextType.Machine, Settings.Default.ipAddress, Settings.Default.username, Settings.Default.password); 
foreach (CheckBox cbx in groupBox1.Controls.OfType<CheckBox>()) 
{ 
    if (cbx.Checked) 
    { 
    UserPrincipal usr = new UserPrincipal(context); 
    if (cbx.Text == "") 
    { 
     usr.Name = txtCustom.Text; 
    } 
    else 
    { 
     usr.Name = cbx.Text; 
    } 
    PrincipalSearcher search = new PrincipalSearcher(usr); 
    PrincipalSearchResult<Principal> results = search.FindAll(); 
    foreach (Principal result in results) 
    { 
     listUsers.AddUser(new windowsUserEntry((UserPrincipal)result)); 
    } // foreach (Principal result in results) 
    }//if (cbx.Checked) 
}//foreach (CheckBox cbx in groupBox1.Controls.OfType<CheckBox>()) 
XmlSerializer s = new XmlSerializer(typeof(windowsUserList)); 
TextWriter w = new StreamWriter(dlgSave.OpenFile()); 
s.Serialize(w, listUsers); 
w.Close(); 

Windows用戶列表/條目的代碼非常長,所以我將其發佈到pastebin

回答

2

windowsUserEntry類的屬性是隻讀的。 XML序列化只能序列化讀寫屬性

+0

是否有可以在只讀屬性上使用的不同於Serialize的函數? – 2010-01-15 17:42:35

+0

你可以使用DataContractSerializer嗎?你正在運行什麼版本的.NET? – 2010-01-15 18:04:37

+0

我決定只是充實這個類並正確實現setters,對於只讀對象,我創建了一個新的異常,我將OjectIsReadOnly引入setter – 2010-01-17 01:38:25

1

如果爲windowsUserEntry的屬性包含空setter,則可以序列化(但不是反序列化)。或者你可以在setter中拋出一個異常(NotImplementedException?)。我不認爲有任何其他方式可以將您的對象序列化爲實現自己的Xml序列化。