XMLSerializer不写入列表中的元素
问题描述:
我正在编写一个程序,该程序基本上会为本地计算机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
答
windowsUserEntry
类的属性是只读的。 XML序列化只能序列化读写属性
答
如果为windowsUserEntry的属性包含空setter,则可以序列化(但不是反序列化)。或者你可以在setter中抛出一个异常(NotImplementedException?)。我不认为有任何其他方式可以将您的对象序列化为实现自己的Xml序列化。
是否有可以在只读属性上使用的不同于Serialize的函数? – 2010-01-15 17:42:35
你可以使用DataContractSerializer吗?你正在运行什么版本的.NET? – 2010-01-15 18:04:37
我决定只是充实这个类并正确实现setters,对于只读对象,我创建了一个新的异常,我将OjectIsReadOnly引入setter – 2010-01-17 01:38:25