简体   繁体   English

为什么我的linq查询投影模型类中的一项?

[英]Why my linq query projecting one item in the model class?

I have more than one item in xml file and want to print all of them. 我在xml文件中有多个项目,并希望将它们全部打印出来。 But for some reason, it is only printing first item from the xml file. 但是由于某种原因,它仅打印xml文件中的第一项。

Here is my xml file. 这是我的xml文件。 stored in the database table in a column called XmlFile:- 存储在数据库表中名为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>

Here is my model class:- 这是我的模特班:-

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

    }

And Linq:- 和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));
}

Output:- 输出: -

Name = One 名称=一

You are always getting first item of the root, you need: 您总是获得根的第一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,
            };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM