2012-02-11 28 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