【发布时间】:2010-11-09 09:14:43
【问题描述】:
我已经设置了一个 xml 序列化/反序列化来在我的应用程序中保存数据。我可以反序列化非数组元素,但是当我反序列化一个数组时,它是空的。我有一种预感,问题出在我试图序列化/反序列化的属性的设置部分。
首先是我要序列化的类:
namespace kineticMold
{
[Serializable()]
public class Config
{
public Config() { }
public string ComPort
{
get
{
return comPort;
}
set
{
comPort = value;
}
}
[XmlArrayItem("recentFile")]
public string[] LastOpen
{
get
{
return lastOpen;
}
set
{
ArrayList holderList = new ArrayList();
holderList.Add(value);
for (int i = 0; i < 4; i++)
{
holderList.Add(lastOpen[i]);
}
lastOpen = (string[])lastOpen.ToArray<string>();
}
}
private string comPort;
private string[] lastOpen = new string[5];
}
}
序列化结果:
<?xml version="1.0" encoding="utf-8" ?>
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ComPort>COM12</ComPort>
<LastOpen>
<recentFile>test.xml</recentFile>
<recentFile xsi:nil="true" />
<recentFile xsi:nil="true" />
<recentFile xsi:nil="true" />
<recentFile xsi:nil="true" />
</LastOpen>
</Config>
反序列化代码:
_cf = new Config();
XmlSerializer ser = new XmlSerializer(typeof(Config));
if (File.Exists(settings_filepath))
{
FileStream fs = new FileStream(@settings_filepath, FileMode.Open);
_cf = (Config)ser.Deserialize(fs);
fs.Close();
}
读取反序列化数据的代码:
for (int i = 0; i < _cf.LastOpen.Length; i++)
{
if (_cf.LastOpen[i] != null)
{
toolStripMenuItem1.DropDownItems.Add(_cf.LastOpen[i]);
recentState = true;
}
}
【问题讨论】:
-
你试过用 List
代替吗? -
@Sotmenet - 列表是否更适合序列化?还没试过。尝试了一个 Arraylist,但失败得很惨。
-
不,它没有任何区别,但它可能对您作为用户更有用。
标签: c# xml serialization