c# - 使用 XmlSerializer 反序列化 XML 时保留纯空白元素内容

标签 c# .net xml whitespace xmlserializer

我有一个类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>

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# - 使用 XmlSerializer 反序列化 XML 时保留纯空白元素内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33152837/

相关文章:

c# - 如何更改 Short 中的位

c# - JavaScriptSerializer 无效的 JSON 原语

c# - 如何删除 OWIN 中的中间件?

python - 将 XML 保存为变量中的 ctypes c_byte 会给出 TypeError : an integer is required

c# - 如何从 Asp Web API 返回单个 DataRow 对象?

.NET ZIP 库在内存中工作

c# - 无法加载文件或程序集或其依赖项之一。该系统找不到指定的文件。 (不允许 GAC)

java - 读取 jar 包中的 xml 文件

java - Java 中最好的 XML 处理类

c# - 我可以在单层或使用的每一层中注册所有 IoC 容器组件吗?