【问题标题】:Why my linq query projecting one item in the model class?为什么我的 linq 查询会在模型类中投影一项?
【发布时间】:2015-05-29 15:40:46
【问题描述】:

我在 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));
}

输出:-

名字 = 一个

【问题讨论】:

    标签: c# asp.net linq asp.net-mvc-5


    【解决方案1】:

    你总是得到第一个 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,
                };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      • 2014-06-08
      • 1970-01-01
      相关资源
      最近更新 更多