问题
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();
}
回答1:
Use the XElement to String conversion operator instead of the Value property:
var tutorials = from tutorial in xmlDoc.Root.Elements("Tutorial")
select new
{
Author = (string)tutorial.Element("Author"),
Title = (string)tutorial.Element("Title"),
Date = (DateTime)tutorial.Element("Date"),
};
回答2:
Instead of referencing the Value
property of the XElement
that might be null, you can do an explicit cast to string instead, like this:
Author = (string) tutorial.Element("Author")
Check out this article for more info:
- Improving LINQ Code Smell with Explicit and Implicit Conversion Operators
来源:https://stackoverflow.com/questions/8177864/how-to-exclude-null-blocks-from-xml-using-linq-to-xml