XML Linq 学习笔记
阅读原文时间:2024年07月05日阅读:1

XML如下:


清新芦荟 饮料 5 薄荷汽水 饮料 本店特色 5

读取方法:

    public List<Dish> GetAllDishes()  
    {  
        List<Dish> dishList = new List<Dish>();  
        string xmlFileName = System.IO.Path.Combine(Environment.CurrentDirectory, @"Data\\Data.xml");  
        //读取XML  
        XDocument xDoc = XDocument.Load("xmlFileName");  
        //返回Dishes集合  
        var dishes = xDoc.Descendants("Dish");  
        //循环集合 ,把数据添加到List中  
        foreach(var d in dishes)  
        {  
            Dish dish = new Dish();  
            dish.Name = d.Element("Name").Value;  
            dish.Category = d.Element("Category").Value;  
            dish.Comment = d.Element("Comment").Value;  
            dish.Score = double.Parse(d.Element("Score").Value);  
            dishList.Add(dish);  
        }  
        return dishList;  
    }