Note that there are some explanatory texts on larger screens.

plurals
  1. POBuilding an object list with Linq to Xml
    primarykey
    data
    text
    <p>I am trying to extract values from an XML file using linq to create a list of objects. The XML File looks like this.</p> <pre><code>&lt;RootNode&gt; &lt;Node1&gt; &lt;Node2&gt; &lt;results&gt; &lt;work&gt; &lt;title&gt;title1&lt;/title&gt; &lt;author&gt;author&lt;/author&gt; &lt;image_url&gt;image&lt;/image_url&gt; &lt;/work&gt; ... &lt;/RootNode&gt; XDocument results = XDocument.Load("url"); </code></pre> <p>There can be multiple occurrences of these 'work' nodes (and subsequent child nodes) depending on the search. For each occurrence of 'work' I want to extract the title/author/image values to build a simple book object:</p> <pre><code>public class Book { public string Title { get; set; } public string Author { get; set; } public string ImageUrl { get; set; } } </code></pre> <p>Now I can iterate through the xml file and pick out indivual values using something like this:</p> <pre><code>foreach (XElement element in results.Descendants("title")) { string title = element.Value; } </code></pre> <p>but as I want to build a list of books I have been trying various things much like this:</p> <pre><code>List&lt;Book&gt; books = (from book in results.Descendants("work") select new Book { Title = book.Element("title").Value, Author = book.Element("name").Value, ImageUrl = book.Element("image_url").Value, }).ToList&lt;Book&gt;(); </code></pre> <p>However I keep getting a null reference exceptionfor this. Any pointers of where I am going wrong would be greatly appreciated.</p> <p>Kevin.</p> <p><strong>EDIT</strong></p> <p>Hi guys turns out the problem was with the XML file and not the linq statement. Thanks.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload