2012-09-14 19 views
0

我需要顯示空或零,而不是顯示空字符串。替換string.empty並顯示「空」使用LINQ到XML?

XML響應:

<Items> 
    <Item> 
    <ASIN>111</ASIN> 
     <ItemAttributes> 
     <Title>xxx</Title> 
     <ListPrice> 
     <Currency>USD</Currency> 
     <FormattedPrice>45.25</FormattedPrice> 
     </ListPrice> 
     </ItemAttributes> 
     <Variation> 
     <Item> 
     <ItemAttributes> 
      <Title>yes</Title> 
      </ItemAttributes> 
     </Item> 
     </Variation> 
    </Item> 
    <Item> 
    <ASIN>222</ASIN> 
     <ItemAttributes> 
     <Title>yyy</Title> 
     </ItemAttributes> 
     <Variation> 
     <Item> 
     <ItemAttributes> 
      <Title>No</Title> 
      </ItemAttributes> 
     </Item> 
     </Variation> 
    </Item> 
    <Items> 

這裏是我的代碼,

var Price1 = xd.Descendants(ns + "ListPrice").Select(c => new 
{ 
    PPrice = (c.Element(ns + "FormattedPrice") != null) ? 
      c.Element(ns + "FormattedPrice").Value : **string.Empty** 
}).ToList(); 

如何與像 「空」 或提前0。謝謝值替換的String.Empty。 如果「格式化價格」對於第二項不可用,則從Xml響應中獲得,它應該在列表中顯示或爲空。

+0

哪種情況爲空,哪種情況爲0? –

+0

@CuongLe如果條件失敗,這裏顯示string.empty。而不是我必須顯示任何文字它可能是「空」或數字「0」。 –

+0

你可以把0放在這個地方? –

回答

1

不清楚爲什麼你在這裏使用匿名類型,如果你使用顯式的string轉換,你也可以避免使用條件運算符。當然,你可以很容易地將string.Empty更改爲"null"真的應該可以正常工作 - 如果不是,那麼還有其他問題。

不管怎麼說,這是一個使用「零」,而不是簡單的代碼(以及更傳統的變量名):

var prices = xd.Descendants(ns + "ListPrice") 
       .Select(c => ((string) c.Element(ns + "Price")) ?? "0") 
       .ToList(); 

這是可能的,你不需要圍繞(string) c.Element(ns + "FormattedPrice")括號 - 我不記得隨便什麼在演員或空合併操作員之外具有更高的優先級。

編輯:爲了應對那裏沒有ListPrice元素,如果你在一個單項水平已位於情況你可以使用:

var price = (string) item.Element(ns + "ListPrice").Element(ns + "Price") ?? "0"; 

獲得價格清單,並以某種方式推斷在ListPrice不存在的情況下插入「0」的位置需要您找到Items,例如

var prices = xd.Descendants(ns + "Item") 
       .Select(item => item.Elements("ListPrice") 
            .Select(c => (string) c.Element(ns + "Price")) 
            .FirstOrDefalut() ?? "0") 
       .ToList(); 

是價格,雖然這將是非常奇怪的,而不是其他項目的數據。

+0

@Thirisangu:除了'Priceted'FormattedPrice' ''和''Null''爲''0'',不清楚你認爲我的答案不會起作用 –

+0

@Thirisangu:你的XML在任何地方都不包含FormattedPrice *,並且你寫道:「from如果「價格」不適用於第二項,則返回Xml響應「如果持續存在不一致,那麼不可能給出一個好的答案,如果」ListPrice「完全不可用,您從未提及過您希望發生的情況。我的代碼不會返回null - 它將返回一個空列表,這不是一回事。另外,如果ListPrice不可用,這與問題的大部分討論的情況完全不同。 –

+0

那是我的錯誤沒有給你足夠的信息。但是你的代碼是正確的。現在我改變了。謝謝 –

0

這是上述問題的解決方案。

var Title = xd.Descendants(ns + "Items").Elements(ns + "Item").Select(DVDTitle =>DVDTitle.Elements(ns + "ItemAttributes").Select(DVDTitle1 => (string)DVDTitle1.Element(ns + "Title")).FirstOrDefault() ?? "Null").ToList();