pearcewg
pearcewg

Reputation: 9593

linq NullReferenceException question

I have a linq query to a XML dataset, which when executed is generating a NullReferenceException.

XDocument dataDoc = XDocument.Load(new StringReader(e.Result));

var Genres = from genre in dataDoc.Descendants("genres")
  where (!genre.Element("ID").IsEmpty)
  select (string)genre.Element("id").Value + ',' + (string)genre.Attribute("name").Value + ',' + (string)genre.Attribute("url").Value;

foreach (string myGenre in Genres)
{
}

When executed, the Linq query works fine, but when the code attempts to iterate through the foreach loop, the NullReferenceException occurs.

Now, i think that the issue has to do with the XML data I am reading, which looks like the following:

<genres>
  <translated>true</translated>
  <genre name="1">
    <id>28</id>
    <url>http://url1</url>
  </genre>
  <genre name="2">
    <id>12</id>
    <url>http://url2</url>
  </genre>
</genres>

Is the first child node, which is different in structure, causing the issue? My class behind this shouldn't be an issue, but is the following (just in case):

public class Genre
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string URL { get; set; }
}

Upvotes: 1

Views: 365

Answers (2)

SLaks
SLaks

Reputation: 888243

genre.Attribute("url") returns null, since there is no url attribute.
You need to call Element, not Attribute.

EDIT: Calling dataDoc.Descendants("genres") returns the single <genres> element, which is not what you want.
You need to call Descendants("genre") (singular) to get the individual <genre ...> elements.
You could also call dataDoc.Descendants("genres").Elements to get the elements inside the <genres> element.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503934

SLaks has pointed out the mistake in using Attribute rather than Element, but there's another improvement you can make in your code. Currently you're using the Value property and then redundantly casting to string. If you just cast an XAttribute or XElement to string, then if the original reference is null, the result will be null as well, rather than an exception being thrown. There's no point in using Value and casting.

Upvotes: 1

Related Questions