簡體   English   中英

Linq to Xml - 輸入字符串

[英]Linq to Xml - Input String

我使用Linq to Xml來解析來自遺留系統的一些xml消息。 其中一條消息以名稱/值對形式出現。 所以我按名稱進行查找,然后嘗試獲取等效值。 但是,當值為空( <Value/> )時,我的代碼拋出錯誤Input string was not in a correct format.

我試圖找出解決這個問題的最佳方法。 任何建議都會非常感激(嘗試使用nullable int type 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>

始終欣賞反饋/輸入。

謝謝,

小號

當element為空時,它的值是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();

已經提供了正確的答案,但我認為更多的解釋會有所幫助。

整個事情是關於XElementNullable<T>顯式轉換 注意這個例子,看看發生了什么:

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 ,其中element為null 否則,處理int解析,只要XElement.Value不是整數就會拋出異常(就像在out情況下,沒有Value ,所以它就像int.Parse(String.Empty) )。

您必須檢查是否is XElement setdoes XElement has value在轉換之前does 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;

使用內聯語句可以輕松完成的任務:

(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;

這應該工作:

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM