c# – 在使用XmlSerializer反序列化XML时保留仅空白元素内容

我有一个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”属性标记的重要空格.

相关文章

C#项目进行IIS部署过程中报错及其一般解决方案_c#iis执行语句...
微信扫码登录PC端网站应用的案例(C#)_c# 微信扫码登录
原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...