从xml文件中读取问题c#

时间:2017-05-15 16:57:57

标签: c# xml xml-serialization streamreader

我正在尝试从xml文件中读取但是它没有工作,尽管我已经在它上面花了两天,所以任何帮助都将非常感谢!

在Cookbook课程中:

  public List<Recipe> readAll()
    {
        List<Recipe> newListRecipies = new List<Recipe>();
        Recipe readRecipie = new Recipe();
        TextReader reader = null;
        try
        {
            var serializer = new XmlSerializer(typeof(Recipe));
            reader = new StreamReader(path);
            newListRecipies = BinarySerialization.ReadFromBinaryFile<List<Recipe>>(path);
            reader.Close();
            return newListRecipies;
        }
        catch (Exception e)
        {
            string error = $"An exception occured: " + e;
            Log theLog = new Log();
            theLog.LogMessage(error);
            return newListRecipies;
        }
    }

在Recipe课程中:

 public Recipe readOne(string name)
    {
        CookBook newCB = new CookBook();
        List<Recipe> allRecipies = newCB.readAll();
        foreach(Recipe oneRecipe in allRecipies)
        {
            if(oneRecipe.recipeName == name)
            {
                return oneRecipe;
            }
        }return newCB.defaultRecipie;
    }

我每次都会得到默认食谱作为结果。我可以看到每次都正确保存收件人但是反正这里代码:

在Recipie课程中:

 public void SaveRecipe(Recipe myRecepie)
    {
        CookBook theCookBook = new CookBook();
        theCookBook.Save(myRecepie);
        addFoodItem(myRecepie.recipeIngridients);
    }

在CookBook课程中:

  public void Save(Recipe newRecipie) 
    {
        TextWriter writer = null;
        try
        {
            var serializer = new XmlSerializer(typeof(Recipe));
            writer = new StreamWriter(path, append: true);
            serializer.Serialize(writer, newRecipie);
        }
        finally
        {
            if (writer != null)
                writer.Close();
        }
    }

和xml文件(由CookBook类中的save函数生成)

    <?xml version="1.0" encoding="utf-8"?>
    <Recipe xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <recipeName>toast</recipeName>
    <recipeType>snack</recipeType>
    <recipeIngridients>
    <string>bread</string>
    <string>butter</string>
    </recipeIngridients>
    </Recipe><?xml version="1.0" encoding="utf-8"?>
    <Recipe xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <recipeName>G&amp;T</recipeName>
    <recipeType>drink</recipeType>
    <recipeIngridients>
    <string>tonic</string>
    <string>gin</string>
    </recipeIngridients>
    </Recipe><?xml version="1.0" encoding="utf-8"?>
    <Recipe xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <recipeName>cake</recipeName>
   <recipeType>snack</recipeType>
   <recipeIngridients>
     <string>butter</string>
     <string>sugar</string>
   </recipeIngridients>
   </Recipe>  

2 个答案:

答案 0 :(得分:0)

我相信你使用BinarySerialization.ReadFromBinaryFile来解析xml的方式是不正确的。

假设你的xml是正确的,我会做这样的事情。

// read file
List<Recipe> recipes;
using (var reader = new StreamReader("recipe.xml"))
{
    XmlSerializer deserializer = new XmlSerializer(typeof(List<Recipe>),  
        new XmlRootAttribute("Recipe"));
    recipes = (List<Recipe>)deserializer.Deserialize(reader);
}

答案 1 :(得分:0)

这些是我所做的改变。最好加载以前的配方,添加到列表中,然后从头开始重写XML。

public class Recipe
{
    public string recipeName;
    public string recipeType;
    public List<string> recipeIngridients = new List<string>();

    public Recipe readOne(string name)
    {
        CookBook newCB = new CookBook();
        List<Recipe> allRecipies = newCB.readAll();
        foreach(Recipe oneRecipe in allRecipies)
        {
            if(oneRecipe.recipeName == name)
            {
                return oneRecipe;
            }
        }
        return newCB.defaultRecipe;
    }
}

public class RecipeList
{
    public List<Recipe> Recipes = new List<Recipe>();
}

public class CookBook
{
    public Recipe defaultRecipe; 
    public string path;

    public void Save(Recipe newRecipe) 
    {
        TextWriter writer = null;
        RecipeList recipeList = null;
        try
        {
            // See if recipes exists
            var serializer = new XmlSerializer(typeof(RecipeList));
            if (File.Exists(path)) // Load the recipe list if it exists
            {
                using (var fileStream = File.OpenRead(path))
                {
                    recipeList = (RecipeList)serializer.Deserialize(fileStream);
                }
            }
            else
            {
                recipeList = new RecipeList();
            }

            // Add recipe to the list
            recipeList.Recipes.Add(newRecipe);
            writer = new StreamWriter(path, append: false);
            serializer.Serialize(writer, recipeList);
        }
        finally
        {
            if (writer != null)
                writer.Close();
        }
    }

    public List<Recipe> readAll()
    { 
        RecipeList temp = null;
        var serializer = new XmlSerializer(typeof(RecipeList));
        try
        {
            using (var fileStream = File.OpenRead(path))
            {
                temp = (RecipeList)serializer.Deserialize(fileStream);
            }
            return temp.Recipes;
        }
        catch (Exception e)
        {
            string error = @"An exception occured: " + e;
            //Log theLog = new Log();
            //theLog.LogMessage(error);
            return new List<Recipe>();
        }
    }
}