2012-02-11 29 views
0

我一直在使用LINQ to XML,并且一直存在问题。我真的很感激任何帮助。我是LINQ to XML的新手,但我发现很容易处理。当没有汇总节点时出现LINQ to XML异常

我有两个不同的联合供稿,我使用联盟汇总到一个联合供稿源。最终的联合供稿包含10个项目。

我正尝试使用XDocument和XElement将联合供稿写入XML文件。我已经能够成功地完成大部分任务。但是,Feed中的某些项目没有描述作为节点元素。当我到达没有这个节点元素的项目时,我得到一个Exception,因为我没有一个项目的描述节点。在我开始编写XML文件之前,如何检查项目以查看是否存在称为描述的节点?如果该项目不包含描述节点,我如何使用默认值填充它?你可以给我建议任何解决方案吗?谢谢你的所有时间!

SyndicationFeed combinedfeed = new SyndicationFeed(newFeed1.Items.Union(newFeed2.Items).OrderByDescending(u => u.PublishDate)); 

//save the filtered xml file to a folder 
XDocument filteredxmlfile = new XDocument(
      new XDeclaration("2.0", "utf-8", "yes"), 
      new XElement("channel", 
      from filteredlist in combinedfeed.Items 
      select new XElement("item", 
        new XElement("title", filteredlist.Title.Text), 
        new XElement("source", FormatContent(filteredlist.Links[0].Uri.ToString())[0]), 
        new XElement("url", FormatContent(filteredlist.Links[0].Uri.ToString())[1]), 
        new XElement("pubdate", filteredlist.PublishDate.ToString("r")), 
        new XElement("date",filteredlist.PublishDate.Date.ToShortDateString()), 
// I get an exception here as the summary/ description node is not present for all the items in the syndication feed 
new XElement("date",filteredlist.Summary.Text) 
       ))); 
string savexmlpath = Server.MapPath(ConfigurationManager.AppSettings["FilteredFolder"]) + "sorted.xml"; 
filteredxmlfile.Save(savexmlpath); 

回答

0

只是检查null

new XElement("date",filteredlist.Summary !=null ? filteredlist.Summary.Text : "default summary") 
+0

你好BorkenGlass, 谢谢您的答复。我使用了上面提供的代码,但它给了我一个对象空引用异常。所以,我将它改为: 新的XElement(“description”,filteredlist.Summary.Text!= null?filteredlist.Summary.Text:“default summary”) 当我这样做的时候,它甚至没有创建这个节点元素xml文件。没有例外nothing.I不知道,但我想我需要的方式来检查是否在我开始写入XML文件之前,每个联合供稿项目中存在描述节点。感谢您的时间! – san0428 2012-02-11 07:49:01