2010-04-07 100 views
22

我使用LINQ和XDocument一起讀取XML文件。這是代碼:使用XDocument&Linq讀取XML - 檢查元素是否爲NULL?

XDocument xml = XDocument.Load(filename); 

var q = from b in xml.Descendants("product") 
     select new 
     { 
      name = b.Element("name").Value, 
      price = b.Element("price").Value,      
      extra = b.Element("extra1").Value, 
      deeplink = b.Element("deepLink").Value     
     }; 

現在的問題是,在extra1領域並不總是存在。沒有該節點的XML文件中有項目。如果發生這種情況,它會與NullReferenceException一起崩潰。

有沒有可能包含「檢查是否爲空」,以便我可以防止它崩潰?

回答

41

使用(string)代替.Value

var q = from b in xml.Descendants("product") 
     select new 
     { 
      name = (string)b.Element("name"), 
      price = (double?)b.Element("price"),      
      extra = (string)b.Element("extra1"), 
      deeplink = (string)b.Element("deepLink")     
     }; 

這也適用於other datatypes,其中包括許多可空類型的情況下,該元素並不總是存在。

+5

+1 - 有趣。 – womp 2010-04-07 17:39:52

7

您可以使用「空合併」運營商:

var q = from b in xml.Descendants("product") 
     select new 
     { 
      name = (string)b.Element("name") ?? "Default Name", 
      price = (double?)b.Element("price") ?? 0.0,      
      extra = (string)b.Element("extra1") ?? String.Empty, 
      deeplink = (string)b.Element("deepLink") ?? String.Empty     
     }; 

這種方式,你將有大約當沒有元素使用默認值完全控制。

+2

'價格'需要是'雙重',因爲這條線是有意義的。 – AakashM 2010-04-08 06:38:45

1

以下是使用XDocument讀取XML文件的示例示例。

XDocument objBooksXML = XDocument.Load(Server.MapPath("books.xml")); 
    var objBooks = from book in 
        objBooksXML.Descendants("Book") 
        select new { 
           Title = book.Element("Title").Value, 
           Pages = book.Element("Pages").Value 
           }; 

    Response.Write(String.Format("Total {0} books.", objBooks.Count())); 
    gvBooks.DataSource = objBooks; 
    gvBooks.DataBind(); 
+0

這段代碼的問題在於,如果「Book」不包含「標題」或「頁面」元素,則在嘗試從其中任何一個獲取.Value時,會拋出空異常。 – Bil 2014-01-01 18:11:58

2

使用以下示例在使用該元素之前檢查是否存在任何元素。

if(b.Elements("extra1").Any()) 
{ 
    extra = b.Element("extra1").Value; 
}