我有一个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);
它就像一个冠军!简单的东西,除了我需要在反序列化时保留成员函数中的空格.生成的XML文件表明序列化时保留了空格,但在反序列化时丢失了.
<IncludeExcludeRules> <IncludeExcludeRule> <Idx>17</Idx> <Name>LIEN</Name> <Operation>E =</Operation> <Function> </Function> </IncludeExcludeRule> </IncludeExcludeRules>
MSDN documentation for XmlAttributeAttribute似乎在标题备注下解决了这个问题,但我不明白如何使用它.它提供了这个例子:
// Set this to 'default' or 'preserve'. [XmlAttribute("space",Namespace = "http://www.w3.org/XML/1998/namespace")] public string Space
咦?设置“默认”或“保留”的内容?我确定我很接近,但这只是没有意义.我必须认为只有一行XmlAttribute在成员之前插入类中以在反序列化时保留空格.
在这里和其他地方有许多类似问题的实例,但它们似乎都涉及使用XmlReader和XmlDocument,或者涉及单个节点等.我想避免这种深度.
解决方法
要在XML反序列化期间保留所有空格,只需创建并使用XmlReader:
StreamReader sr = new StreamReader(path); XmlReader xr = XmlReader.Create(sr); XmlSerializer reader = new XmlSerializer(typeof(InputConfig)); InputConfig inputConfig = (InputConfig)reader.Deserialize(xr);
与XmlSerializer.Deserialize(XmlReader)不同,XmlSerializer.Deserialize(TextReader)
仅保留由xml:space =“preserve”属性标记的重要空格.