0

This question is a follow up from this.

When I try to read inner nodes using linq, it does not give me back the collection as expected, but rather gives me only one item. Please see the test.

   [Test]
        public void Should_get_all_items()
        {
            var item = "<Item status=\"SUCCESS\""+
            " message=\"\">" +
            "<ItemDate>12/21/2012" +
            "<ItemType>MyType1" +
            "<ItemUrl title=\"ItemTitle\">http://www.itemurl1.com</ItemUrl>" +
            "</ItemType>" +
            "</ItemDate>" +
            "<ItemDate>12/22/2012" +
            "<ItemType>MyType2" +
            "<ItemUrl title=\"Item2Title\">http://www.itemurl2.com</ItemUrl>" +
            "</ItemType>" +
            "</ItemDate>" +
            "</Item>";

            XDocument xdoc = XDocument.Parse(item);
            var query = from i in xdoc.Descendants("Item")
                        let date = i.Element("ItemDate")
                        let type = date.Element("ItemType")
                        let url = type.Element("ItemUrl")
                        select new ItemDate()
                        {
                            Date = ((XText)date.FirstNode).Value,
                            Type = ((XText)type.FirstNode).Value,
                            Url = (string)url,
                            Title = (string)url.Attribute("title"),
                        };

            var qItems = query.ToList();
            Assert.That(qItems.Count, Is.EqualTo(2));
        }

 public class ItemDate
    {
        public string Date { get; set; }
        public string Type { get; set; }
        public string Url { get; set; }
        public string Title { get; set; }
    }

The above test fails.Any idea what is going wrong here? I think the name Item is bit misleading here as I'm after the collection of ItemDates

Thanks, -Mike

Community
  • 1
  • 1
Mike
  • 3,204
  • 8
  • 47
  • 74

2 Answers2

1
var items = xdoc.Descendants("ItemDate")
    .Select(e => new ItemDate
    {
        Date = e.FirstNode.ToString(),
        Type = e.Element("ItemType").FirstNode.ToString(),
        Url = e.Element("ItemType").Element("ItemUrl").Value,
        Title = e.Element("ItemType").Element("ItemUrl").Attribute("title").Value
    })
    .ToList();
L.B
  • 114,136
  • 19
  • 178
  • 224
0

The test fails because your XML only has one Item node and thus you only have one result.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443