Consider this XML file. Note the first Tutorial has an Author child element, and the second Tutorial does not:
<?xml version="1.0" encoding="utf-8" ?>
<Tutorials>
<Tutorial>
<Author>The Tallest</Author>
<Title>
WPF Tutorial - Creating A Custom Panel Control
</Title>
<Date>2/18/2008</Date>
</Tutorial>
<Tutorial>
<Title>
2nd WPF Tutorial - Creating A Custom Panel Control
</Title>
<Date>2/18/2008</Date>
</Tutorial>
</Tutorials>
How do I use LINQ-to-XML to load the data that is present? The code below blows up when it gets to the Tutorial section that lacks an author. I cannot figure out how to write the where statement to exclude the block that lacks an author, or how to make the code elegantly skip over the missing data. I have tried this:
where tutorial.Element("Title") != null
But the above has no effect.... Here is the problem code:
XDocument xmlDoc = XDocument.Load("C:\\xml\\2.xml");
var tutorials = from tutorial in xmlDoc.Descendants("Tutorial")
select new
{
Author = tutorial.Element("Author").Value,
Title = tutorial.Element("Title").Value,
Date = tutorial.Element("Date").Value,
};
foreach (var tutorial in tutorials)
{
Console.WriteLine("author: " + tutorial.Author);
Console.ReadKey();
}