开发者

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; }
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜