2016-03-15 44 views
1

XElement明確支持將結果轉換爲空值<int>但它不能正常工作。下面的單元測試演示了這個問題:將XElement轉換爲int?當指定xsi:nil =「true」時失敗

[TestMethod] 
    public void CastingNullableInt() 
    { 
     var xdoc = XDocument.Parse("<root xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><okay>123</okay><boom xsi:nil=\"true\"/></root>"); 
     Assert.AreEqual(123, (int?)xdoc.Root.Element("okay")); 
     Assert.IsNull((int?)xdoc.Root.Element("boom")); 
    } 

測試應該通過最後的斷言。相反,它給出FormatException

輸入字符串格式不正確。

爲什麼不在這裏正確解析null

+1

定義 –

+0

我期望單元測試通過「不按預期工作」。我怎麼可能做得更清楚? –

+0

@PatrickHofman感謝您改善我的問題! –

回答

0

XElement沒有正確解析<boom xsi:nil=\"true\"/>。它只適用於您省略<boom xsi:nil=\"true\"/>,則值爲null並返回(int?)null

一種解決辦法可能是先檢查上不爲空值:

!string.IsNullOrEmpty((string)xdoc.Root.Element("boom")) 
    ? (int?)xdoc.Root.Element("boom") 
    : null 
    ; 
+0

我很害怕這種情況,但我想把它扔在那裏,看看我是否失去了明顯的東西。感謝Patrick! –

+0

對不起,我不能幫你這個。我希望你的解決方法已經足夠。 –

1

的LINQ to XML不知道的模式,這樣就不會轉換xsi:nil = "true"爲可空變量。爲了驗證這一點,你需要做的是這樣的:

Assert.IsTrue((bool?)xdoc.Root.Element("boom").Attribute("{http://www.w3.org/2001/XMLSchema-instance}nil") == true); 
0

您可以檢查IsEmpty屬性:

var value = xdoc.Root.Element("boom").IsEmpty ? null : (int?)xdoc.Root.Element("boom"); 
相關問題