如何使用 LINQ-to-XML 从 XML 中排除 NULL 块?
考虑这个 XML 文件。请注意,第一个教程有一个 Author 子元素,而第二个教程没有:
<?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?当下面的代码到达缺少作者的教程部分时,就会崩溃。我不知道如何编写 where 语句来排除缺少作者的块,或者如何使代码优雅地跳过丢失的数据。我已经尝试过:
where tutorial.Element("Title") != null
但是上面没有效果......这是问题代码:
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();
}
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 XElement 到字符串转换运算符 而不是 值属性:
Use the XElement to String conversion operator instead of the Value property:
您可以显式转换为字符串,而不是引用可能为 null 的
XElement
的Value
属性,如下所示:查看本文以获取更多信息:
Instead of referencing the
Value
property of theXElement
that might be null, you can do an explicit cast to string instead, like this:Check out this article for more info: