Skip to main content
 首页 » 编程设计

元素的 c# LINQ to XML 查询表达式是否存在

2024年02月24日17mayingbao

<channel> 
        <title>Best Web Gallery - Flash + CSS Gallery</title> 
        <link>http://bestwebgallery.com</link> 
        <description>Featuring the world best web design</description> 
        <pubDate>09 Dec 2009</pubDate>     
        <generator>http://wordpress.org/?v=2.3.2</generator> 
        <language>en</language> 
</channel>    
 
 
<channel> 
        <title>Best Web Gallery - Flash + CSS Gallery</title> 
        <link>http://bestwebgallery.com</link> 
        <description>Featuring the world best web design</description> 
 
            // pubDate missing 
 
        <generator>http://wordpress.org/?v=2.3.2</generator> 
        <language>en</language> 
</channel> 
 
 
 
 
   XDocument rssFeed = XDocument.Load(url); 
 
                    var feedResources = from details in rssFeed.Descendants("channel") 
                                    select new feedResource 
                                    { 
                                         Title = details.Element("title").Value, 
                                         Host = details.Element("link").Value, 
                                         Description = details.Element("description").Value,   
 
                                         PublishedOn = DateTime.Parse(details.Element("pubDate").Value),  
                                         Generator = details.Element("generator").Value, 
                                         Language = details.Element("language").Value 
                                    }; 

我们如何在尝试获取元素“pubDate”或其他元素之前检查此处,因为如果不检查,将抛出空引用异常??

请您参考如下方法:

不要使用Parse 等; xml 通常使用与其接受的不同的字符串表示形式;只是施法(注意没有 .Value):

select new FeedResource 
{ 
    Title = (string)details.Element("title"), 
    Host = (string)details.Element("link"), 
    Description = (string)details.Element("description"), 
    PublishedOn = (DateTime?)details.Element("pubDate"), 
    Generator = (string)details.Element("generator"), 
    Language = (string)details.Element("language") 
} 

XElement 具有转换运算符来完成所有工作,返回适当的值。