C#反序列化List <t>问题</t>

时间:2015-03-03 16:59:23

标签: c# xmlserializer

这是我尝试序列化和反序列化的类:

[Serializable]
[XmlRoot("RecipeStepWords")]
public class CRecipeStepsWords
{
    [XmlArray]
    public List<RecipeStep> ReadRecipeSteps { get; set; }
    [XmlArray]
    public List<RecipeStep> WriteRecipeSteps { get; set; }

    public CRecipeStepsWords()
    {
        ReadRecipeSteps = new List<RecipeStep>();
        for (int x = 1; x <= 8; x++)
        {
            ReadRecipeSteps.Add(new RecipeStep());
        }
        WriteRecipeSteps = new List<RecipeStep>();
        for (int x = 1; x <= 6; x++)
        {
            WriteRecipeSteps.Add(new RecipeStep());
        }
    }

    public class RecipeStep
    {
        public String Test1 { get; set; }
        public String Test2 { get; set; }

        public RecipeStep()
        {
            Test1= "Sample 1";
            Test2 = "Sample 2";
        }
    }
}

从代码中可以看出,ReadRecipeSteps应该有8个项目,WriteRecipeSteps应该有6个。但是,每当我多次运行程序时,反序列化列表都会被添加到,即first run = ReadRecipeStesp.Count = 8,第二次运行.Count = 16等。

以下是我反序列化的方法:

if (File.Exists(Path.Combine(path, fName)))
{
    StreamReader objStreamReader = new StreamReader(Path.Combine(path, fName));
    XmlSerializer x = new XmlSerializer(RecipeStepsWords.GetType());

    RecipeStepsWords = (CRecipeStepsWords)x.Deserialize(objStreamReader);
    objStreamReader.Close();
}

我正在使用VS 2010。我想要的是始终在列表中有正确数量的项目,8和6,而不是每次反序列化时都添加它们。任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

尝试添加

[XmlArrayItem(“ReadReceipe”)]紧跟在xml数组之后。 WriteReciepe

也是如此

所以喜欢这个。

    [XmlArray]
    [XmlArrayItem("ReadReceipe")]
    public List<RecipeStep> ReadRecipeSteps { get; set; }

我认为发生的事情是你只是继续将这些步骤添加到根目录,而没有父节点。

让我知道。

答案 1 :(得分:0)

// Reset your object
RecipeStepsWords = new CRecipeStepsWords();
RecipeStepsWords = (CRecipeStepsWords)x.Deserialize(objStreamReader);
objStreamReader.Close();