2011-11-18 71 views
2

考虑这个XML文件。注意第一个教程有作者子元素,第二个教程不:如何使用LINQ-to-XML从XML中排除NULL块?

<?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> 

如何使用LINQ到XML来加载存在的数据?当它到达缺少作者的教程部分时,下面的代码会显示出来。我无法弄清楚如何编写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(); 
} 

回答

3

使用XElement to String conversion operator代替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"), 
       }; 
+0

AHHHHH,这似乎是票!谢谢!! (在我阅读的所有内容中,这种方法并未出现) – Jonesome