2011-06-16 17 views
2

我正在從Web服務接收數據。 XML進來是這樣的:從列表中創建XElement <T>其中T.property爲空

<data> 
    <item> 
     <code>a</code> 
     <price>2.89</price> 
    </item> 
    <item> 
     <code>a</code> 
     <price>2.89</price> 
     <colour>blue</colour> 
    </item> 
</data> 

所以,我們看到一個項目有一個額外的屬性顏色。

好的,這將轉換爲列表<項目>這是我得到它的點。

我需要將此列表轉換爲XDocument。

使用:

var xml = new XDocument(
new XDeclaration("1.0", "utf-16", "yes"), 
new XElement("data", 
from i in myList 
select new XElement("item", 
new XElement("price", i.price), 
new XElement("code", i.code), 
new XElement("colour", i.colour)))); 

(我從記憶中鍵入這一點,所以藉口拼寫)

這裏,錯誤,因爲i.colour爲空。

我該如何應對?

在此先感謝

格里夫

+1

你什麼*想*到當'colour'爲'null'時發生? – AakashM 2011-06-16 11:28:20

回答

3

你要檢查i.colour是否null試圖訪問它。

爲此,您可以用整齊的空合併運算符,如:

new XElement("colour", i.colour ?? "")))); 

假設你想要一個空字符串作爲值,如果i.colournull

UPDATE基於您的評論

下面,如果你不希望加入的元素做,如果i.colour爲null,則independantly的XDocument實例的創建它,並將其添加爲必需的。

var xml = new XDocument(...); 

if(i.colour != null) 
{ 
    xml.Add(new XElement(...)); 
} 

}

+0

毫無疑問,如果屬性顏色爲null,那麼我不想創建XElement。 – DrGriff 2011-06-16 11:52:15

+0

請參閱上面的我的更新。 – 2011-06-16 11:57:51

+0

不幸的是,你的更新並不適合'from ... select'語法。 – 2011-06-16 12:50:43

2

爲了避免增加新的XElementcolour爲空,你可以使用ternary operator和返回null或新XElement酌情:

var xml = new XDocument(
    new XDeclaration("1.0", "utf-16", "yes"), 
    new XElement("data", 
    from i in myList 
    select new XElement("item", 
     new XElement("price", i.price), 
     new XElement("code", i.code), 
     i.colour == null ? 
      null : new XElement("colour", i.colour) 
    ))); 
+0

XElement的Ctor做了什麼? – 2011-06-16 23:29:09

+1

好吧,我檢查:null被忽略,沒有標籤生成。 OP要求的是什麼。 – 2011-06-16 23:33:55