【问题标题】:How does XMLserializer.serialize behave when it has to update a list item with an empty list当必须使用空列表更新列表项时,XMLserializer.serialize 的行为如何
【发布时间】:2014-01-02 13:02:21
【问题描述】:

今天早上我遇到了一个 xml 错误,当我去查找时,我发现了一个看起来像这样的 xml:

<root>   
  <list /> 
<root> var </item> 
<item> var </item> 
</list> 
</root>

这显然是错误的。

代码中唯一可以做到这一点的行如下:

XmlSerializer.Serialize(fileStream, thisObject);

我怀疑它试图用&lt;list /&gt; 更新&lt;list&gt;&lt;item&gt;var&lt;/item&gt;&lt;/list&gt;,然后卡在第一个元素上,因为它立即关闭了它。

有谁知道这个例子中的序列化函数应该如何表现?

编辑:我写了一些代码来重现问题:

using System;
using System.Collections.Generic;
using System.IO;

namespace XMLserializetest
{

    public class sample
    {
        public DateTime LastRun { get; set; }
        public List<int> intlist { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            const string FileName = "c:\\temp\\list.xml";
            var file = new FileStream(FileName, FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);
            try
            {
                var test = new sample();
                test.LastRun = DateTime.Now;
                test.intlist = new List<int>();
/*Comment this line and run again, then look at the xml*/                    
test.intlist.Add(1); test.intlist.Add(2); test.intlist.Add(3); test.intlist.Add(4); 

                var x = new System.Xml.Serialization.XmlSerializer(test.GetType());
                x.Serialize(file, test);
            }
            catch (Exception e)
            {
                var a = e;
            }
            finally
            {
                file.Close();
            }

        }
    }
}

【问题讨论】:

    标签: xml c#-4.0 xml-serialization


    【解决方案1】:

    您应该使用 StreamWriter,以便流知道他不需要追加:

    var file = new StreamWriter(FileName);
    

    对于这个例子,你应该在写入之前首先检查文件是否存在。

    【讨论】:

      【解决方案2】:

      我在加载流之前添加了这一行:

      File.WriteAllText(FileName, string.Empty);
      

      这清空了文件,因此序列化方法没有混淆,一切顺利。

      【讨论】:

      • 我暂时不会排除我自己的答案。我相信必须有一个更清洁的解决方案。
      • FileMode.Create,也许吧?
      猜你喜欢
      • 2013-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      • 2013-08-31
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      相关资源
      最近更新 更多