2013-03-12 56 views
1

我使用Linq to Xml來解析來自遺留系統的一些xml消息。其中一條消息以名稱/值對的形式出現。因此,我正在按名稱進行查找,然後試圖獲得相同的值。但是,當值爲空(<Value/>)我的代碼是拋出錯誤Input string was not in a correct format.Linq to Xml - 輸入字符串

我想弄清楚解決這個問題的最佳方法。任何建議將不勝感激(嘗試填充可爲空int類型int的屬性?)。

代碼示例:

myRecord.myField= xdoc.Descendants("Information") 
         .Where(x => (string)x.Element("Name") == "myField") 
         .Select(x => (int?)x.Element("Value")).FirstOrDefault(); 

XML摘錄:

<Information> 
     <Name>myField</Name> 
     <Value /> 
    </Information> 

始終欣賞反饋/輸入。

謝謝,

小號

回答

3

當元件是空的,那麼它的值是String.Empty不能被解析爲整數。所以,你應該手動處理這種情況下:

myRecord.myField = xdoc.Descendants("Information") 
         .Where(x => (string)x.Element("Name") == "myField") 
         .Select(x => x.Element("Value")) 
         .Select(v => (v == null || v.IsEmpty) ? null : (int?)v) 
         .FirstOrDefault(); 
+1

會拋出NullReferenceException異常時,有沒有這樣的元素(恐怕是沒有的情況下在這裏,但值得知道) – MarcinJuraszek 2013-03-12 15:06:47

+0

@MarcinJuraszek不,它不會這種情況將處理失蹤元素'(v == null || v.IsEmpty)' – 2013-03-12 15:06:58

+0

嗯,你必須更新你的答案,而我正在打字:) – MarcinJuraszek 2013-03-12 15:08:13

0

已經有一個正確的答案提供的,但我認爲,多一點的解釋將是有益的。

整個事情是關於XElement to Nullable<T> explicit conversion。當心那個例子來看看,這是怎麼回事:

XElement element = null; 
// returns null 
int? value = (int?)element; 

element = new XElement("test", 1); 
// returns 1 
value = (int?)element; 

element = new XElement("test"); 
// throws FormatException 
value = (int?)element; 

(int?)xElementInstance回報null只,其中元素是null。否則,int解析被處理,拋出一個異常,每當XElement.Value不是一個整數(如出現的情況下,當沒有Value,所以它就像int.Parse(String.Empty))。

你必須轉換前檢查is XElement setdoes XElement has value

if (element == null) 
    return null; 
else if (element.IsEmpty) 
    return null 
else if (string.IsNullOrEmpty(element.Value)) 
    return null 
else 
    return (int?)element; 

什麼可以使用inline語句很容易做到:

(element == null || element.IsEmpty || string.IsNullOrEmpty(element.Value) ? null : (int?)element) 

綜上所述,下面的代碼做你想做的 - 需要int?來自XElement,當元素沒有值時事件:

element = new XElement("test"); 
// returns null 
value = element == null || element.IsEmpty || string.IsNullOrEmpty(element.Value) ? null : (int?)element; 
+0

如果您使用'XElement。解析(「」)',那麼'IsEmpty'將返回'false',但'Value'將返回一個空字符串,並且轉換將拋出'FormatException'。 – 2013-03-12 17:01:05

+0

你是對的!我不知道,非常感謝!更新了我的答案。 – MarcinJuraszek 2013-03-12 17:16:42

0

這應該工作:

public static class Extensions 
{ 
    public static int? ToInt32(this XElement element) 
    { 
     if (element == null) return null; 
     if (element.IsEmpty) return null; 

     // If the element is declared as <Value></Value>, 
     // IsEmpty will be false, but the value will be an empty string: 
     if (string.IsNullOrEmpty(element.Value)) return null; 

     return XmlConvert.ToInt32(element.Value); 
    } 
} 

myRecord.myField = doc.Descendants("Information") 
    .Where(x => (string)x.Element("Name") == "myField") 
    .Select(x => x.Element("Value").ToInt32()).FirstOrDefault();