我有一个类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; }
}
}
Using ...
FileStream fs = new FileStream(path, FileMode.Create);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(InputConfig));
xmlSerializer.Serialize(fs, this);
fs.Close();
... and ...
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>
XmlAttributeAttribute 的 MSDN 文档似乎在“Remarks”部分解决了这个问题,但我不知道如何使用它。它提供以下示例:// Set this to 'default' or 'preserve'.
[XmlAttribute("space",
Namespace = "http://www.w3.org/XML/1998/namespace")]
public string Space
啥?将什么设置为“default”或“preserve”?我确定我接近正确了,但这似乎毫无意义。我想在成员之前在类中插入一个单行的XmlAttribute以保留反序列化期间的空格。
这里和其他地方有许多类似的问题,但它们似乎都涉及使用XmlReader和XmlDocument,或者深入研究各个节点等。我想避免那种深度。
Function
属性上放置[XmlAttribute("space", Namespace = "http://www.w3.org/XML/1998/namespace")]
时会发生什么?该属性是否被添加? - Panagiotis Kanavospublic string Space ="preserve";
之后就可以了。但是我更喜欢使用下面描述的XmlReader/XmlWriter,因为这样我就可以简单地使用注释[XmlAttribute("xml:space=preserve")]
。 - CDTWF