微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/csharp/91242.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐