2012-02-11 5 views
0

LINQ to XMLを使用していて、問題が残っています。私は本当に助けていただければ幸いです。 LINQ to XMLは初めてのことですが、簡単に使えると感じました。サマリーノードが存在しない場合のLINQ to XML例外

私はUnionを使用して1つのシンジケーションフィードに集約する2つの異なるシンジケーションフィードを持っています。最後のシンジケーションフィードには10個のアイテムが含まれています。

XDocumentとXElementを使用して、XMLファイルにシンジケーションフィードを書き込もうとしています。私は大部分のために成功しました。しかし、フィード内の項目の中には、ノード要素としての記述を持たないものもあります。このノード要素を持たない項目に到達すると、項目の1つに説明ノードがないため、例外が発生します。 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、 はご回答いただきありがとうございます。上記のコードを使用しましたが、オブジェクトのnull参照例外が返されます。したがって、私は次のように変更しました: 新しいXElement( "description"、filteredlist.Summary.Text!= null?filteredlist.Summary.Text: "default summary") これを行うと、このノード要素をxmlファイル。例外は何もありません。わかりませんが、xmlファイルを書き始める前に、記述ノードがそれぞれの配信フィード項目に存在するかどうかを確認する必要があると思います。あなたの時間をありがとう! – san0428