XML Linq 学习笔记

时间:2024-12-16 13:33:44

XML如下:

<?xml version="1.0" encoding="utf-8"?>
<Dishes>
<Dish>
<Name>清新芦荟</Name>
<Category>饮料</Category>
<Comment></Comment>
<Score>5</Score>
</Dish>
<Dish>
<Name>薄荷汽水</Name>
<Category>饮料</Category>
<Comment>本店特色</Comment>
<Score>5</Score>
</Dish>
</Dishes>

读取方法:

        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;
}