我有课InputConfig
其中包含一个List<IncludeExcludeRule>
:
public class InputConfig
{
// The rest of the class omitted
private List<IncludeExcludeRule> includeExcludeRules;
public List<IncludeExcludeRule> IncludeExcludeRules
{
get { return includeExcludeRules; }
set { includeExcludeRules = value; }
}
}
public class IncludeExcludeRule
{
// Other members omitted
private int idx;
private string function;
public int Idx
{
get { return idx; }
set { idx = value; }
}
public string Function
{
get { return function; }
set { function = value; }
}
}
使用 ...
FileStream fs = new FileStream(path, FileMode.Create);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(InputConfig));
xmlSerializer.Serialize(fs, this);
fs.Close();
... 和 ...
StreamReader sr = new StreamReader(path);
XmlSerializer reader = new XmlSerializer(typeof(InputConfig));
InputConfig inputConfig = (InputConfig)reader.Deserialize(sr);
它就像冠军一样工作!简单的事情,除了我需要保留成员中的空格function
反序列化时。生成的 XML 文件表明,序列化时保留了空格,但反序列化时空格丢失。
<IncludeExcludeRules>
<IncludeExcludeRule>
<Idx>17</Idx>
<Name>LIEN</Name>
<Operation>E =</Operation>
<Function> </Function>
</IncludeExcludeRule>
</IncludeExcludeRules>
The XmlAttributeAttribute 的 MSDN 文档似乎在标题下解决了这个问题Remarks,但我不明白如何使用它。它提供了这个例子:
// Set this to 'default' or 'preserve'.
[XmlAttribute("space",
Namespace = "http://www.w3.org/XML/1998/namespace")]
public string Space
啊?将什么设置为“默认”或“保留”?我确信我已经很接近了,但这没有意义。我必须认为只需在类中的成员之前插入一行 XmlAttribute 即可在反序列化时保留空格。
这里和其他地方有很多类似问题的实例,但它们似乎都涉及 XmlReader 和 XmlDocument 的使用,或者对单个节点等进行处理。我想避免那么深。