如何使用Linq从XML获取强类型集合

Sha*_*180 3 c# xml linq asp.net

这是我的XML文件的一个片段(我意识到它的格式并不理想,但遗憾的是我不能改变它):

<PRODMENUS>
<MENU id="90168" shortname="BrdSumPV13" mealname="Dinner" mealid="7" servedate="20130102">Summer PREV 2013</MENU>
<MENU id="90153" shortname="BrdSumPV13" mealname="Breakfast" mealid="46" servedate="20130102">Summer PREV 2013</MENU>
<MENU id="90162" shortname="BrdSumPV13" mealname="Lunch" mealid="6" servedate="20130102">Summer PREV 2013</MENU>
</PRODMENUS>
Run Code Online (Sandbox Code Playgroud)

以下功能有效,但它只抓取第一个菜单元素,而不是其余的

public static List<Menu> GetLocations(string uri)
{
    XDocument xmlDoc = XDocument.Load(uri);
    var menus = from menu in xmlDoc.Elements("PRODMENUS")
                          select new Menu
                          {
                              Id = Convert.ToInt32(menu.Element("MENU").Attribute("id").Value),
                              ShortName = menu.Element("MENU").Attribute("shortname").Value,
                              MealName = menu.Element("MENU").Attribute("mealname").Value,
                              MealId = Convert.ToInt32(menu.Element("MENU").Attribute("mealid").Value)
                          };

    return menus.ToList();
}
Run Code Online (Sandbox Code Playgroud)

如何使用上述XML文件获取3个Menu对象的集合?

I4V*_*I4V 7

你很近

XDocument xmlDoc = XDocument.Load(uri);
var menus = from menu in xmlDoc.Descendants("MENU")
            select new Menu
            {
                Id = Convert.ToInt32(menu.Attribute("id").Value),
                ShortName = menu.Attribute("shortname").Value,
                MealName = menu.Attribute("mealname").Value,
                MealId = Convert.ToInt32(menu.Attribute("mealid").Value)
            };

return menus.ToList();
Run Code Online (Sandbox Code Playgroud)

你也可以使用一些快捷方式Id = (int)menu.Attribute("id")代替Id = Convert.ToInt32(menu.Attribute("id").Value)