2

i need to store all the informationen from the xml in an array. My code doesn't work, because I always get just the first item from the xml.

Does anyone know how to fix this?

            XDocument xdoc = XDocument.Load("http://www.thefaxx.de/xml/nano.xml");
        var items = from item in xdoc.Descendants("items")
                    select new
                    {
                        Title = item.Element("item").Element("title").Value,
                        Description = item.Element("item").Element("description").Value
                    };

        foreach (var item in items)
        {
            listView1.Items.Add(item.Title);
        }
0

1 Answer 1

4

How about:

    var items = from item in xdoc.Descendants("item")
                select new
                {
                    Title = item.Element("title").Value,
                    // *** NOTE: xml has "desc", not "description"
                    Description = item.Element("desc").Value
                };

It is a little hard to be sure without sample xml - but it looks like you intend to loop over all the <item>...</item> elements - which is what the above does. Your original code loops over the (single?) <items>...</items> element(s), then fetches the first <item>...</item> from within it.


edit after looking at the xml; this would be more efficient:

    var items = from item in xdoc.Root.Elements("item")
                select new {
                    Title = item.Element("title").Value,
                    Description = item.Element("desc").Value
                };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.