如何使用LINQ到XML来排除XML NULL块? [英] How to exclude NULL blocks from XML using LINQ-to-XML?

查看:126
本文介绍了如何使用LINQ到XML来排除XML NULL块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个XML文件。注意第一个教程有作者子元素,而第二个教程不:



<预类=郎咸平的XML prettyprint-覆盖> < ?XML版本=1.0编码=UTF-8>?;
<教程>
<&教程GT;
<作者>在最高的< /作者>
<标题>
WPF教程 - 创建自定义面板控制
< /标题>
<日期→2 /二千零八分之十八< /日期和GT;
< /教程>
<&教程GT;
<标题>
第二WPF教程 - 创建自定义面板控制
< /标题>
<日期→2 /二千零八分之十八< /日期和GT;
< /教程>
< /教程>



我如何使用LINQ到XML加载存在的数据?下面的代码鼓起时,它得到的教程部分,缺乏一个作家。我无法弄清楚如何编写WHERE语句排除缺乏一个作家,或者如何使代码优雅的跳过丢失的数据块。我已经试过这样:!



 其中tutorial.Element(标题)= NULL 

但上面没有任何影响....这里的问题是代码:

 的XDocument xmlDoc中= XDocument.Load(C:\\xml\\2.xml);从教程

变种教程=在xmlDoc.Descendants(教程)
选择新的
{
=作者tutorial.Element(作者)。价值,
标题= tutorial.Element(标题)值,
日期= tutorial.Element(日期)值,
}。

的foreach(在教程教程VAR)
{
Console.WriteLine(作者:+ tutorial.Author);
Console.ReadKey();
}


解决方案

使用的的XElement到String的转换操作符代替的 Value属性

 从教程教程变种=以xmlDoc.Root.Elements(教程)
选择新的
{
=作者(串)tutorial.Element(作者),
标题=(字符串)tutorial.Element(标题),
日期=(DateTime的)tutorial.Element(日期),
};


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

解决方案

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"),
                };

这篇关于如何使用LINQ到XML来排除XML NULL块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆