Почему мой запрос linq проецирует один элемент в классе модели?

1

У меня есть несколько элементов в xml файле и вы хотите распечатать их все. Но по какой-то причине он только печатает первый элемент из xml файла.

Вот мой xml файл. хранится в таблице базы данных в столбце XmlFile: -

<root>
  <item name="one" action="GetListOne" print="2" />
  <item name="two" action="GetListTwo" print="1" />
  <item name="three" action="GetListThree" print="2" />
  <item name="four" action="GetListFour" print="0" />
</root>

Вот мой модельный класс: -

 public class ItemList 
    {
        public string Name { get; set; }
        public string Action { get; set; }
        public string Print { get; set; }

    }

И Linq: -

var items = _repo.GetItemsById(Id).Single();
var xml = XDocument.Parse(items.XmlFile);
var model = from x in xml.Descendants("root")
    select new ItemList
    {
        Name = x.Element("item").Attribute("name").Value,
        Action = x.Element("item").Attribute("action").Value,
        Print = x.Element("item").Attribute("print").Value,
    };
foreach (var m in model)
{
    Console.WriteLine(String.Format("Name = {0}",m.Name));
}

Вывод:-

Имя = один

Теги:
linq
asp.net-mvc-5

1 ответ

2
Лучший ответ

Вы всегда получаете первый item корня, вам нужно:

var model = from x in xml.Descendants("item")
            select new ItemList
            {
                Name = x.Attribute("name").Value,
                Action = x.Attribute("action").Value,
                Print = x.Attribute("print").Value,
            };

Ещё вопросы

Сообщество Overcoder
Наверх
Меню