2014-02-24 23 views
0

您好所有我有這個方法檢查是否名單是在C#方法無效

public void insertXmlNode(string XmlParentNodeName, List<string> XmlNodeName, List<string> XmlNodeValue, List<string> XmlAttributeName, List<string> XmlAttributeValue) 
    { 

     XmlDocument xdoc = new XmlDocument(); 
     xdoc.Load(_connection); 
     XmlNode xparent = xdoc.SelectSingleNode("//" + XmlParentNodeName); 
     if (xparent == null) 
     { 
      xparent = xdoc.CreateNode(XmlNodeType.Element, XmlParentNodeName, null); 
      xdoc.DocumentElement.AppendChild(xparent); 
     } 

     for (int i = 0; i <= XmlNodeName.Count; i++) 
     { 
      XmlNode xnode = xdoc.CreateNode(XmlNodeType.Element, XmlNodeName[i], null); 
      xnode.InnerText = XmlNodeValue[i]; 
      if (!string.IsNullOrEmpty(XmlAttributeName.ToString())) 
      { 
       XmlAttribute xattribute = xdoc.CreateAttribute(XmlAttributeName[i]); 
       xattribute.Value = XmlAttributeValue[i]; 
       xnode.Attributes.Append(xattribute); 
      } 
      xparent.AppendChild(xnode); 
     } 

     xdoc.Save(_connection); 
    } 

,我稱之爲象下面這樣:

_db.insertXmlNode("Orders", _orderName, _orderValue, null, null); 

「_db是一類instanc和_orderName & _orderValue有列表字符串「

我想如果XmlAttributeName不爲null add attribu TE到XML節點,但我 得到這個錯誤

值不能爲空

我怎麼能檢查是否XmlAttributeName不爲空做財產以後?

if (XmlAttributeName != null || 
    XmlAttributeName.All(x => string.IsNullOrWhiteSpace(x))) 
{ 
    ....... 
} 

嘗試做這樣:

回答

0

而不是做檢查這種方式,因爲你在評論說的

if (XmlAttributeName != null && 
    XmlAttributeName.All(x => !string.IsNullOrWhiteSpace(x))) 
{ 
    ....... 
} 

隨着&&運營商第2條件將僅在檢查滿足第一個條件。並且代碼執行將輸入if塊,僅當XmlAttribute不爲空並且列表中的所有屬性不爲空或空字符串時。

0
private bool HasInvalidValues(IEnumerable<string> enumerable) 
{ 
    return enumerable == null || enumerable.Any(string.IsNullOrWhiteSpace); 
} 
0

檢查無效的正確方法是if(XmlAttributeName != null)。這種檢查無處不在的參考類型;即使Nullable<T>覆蓋相等運算符是檢查無效性時表示nullable.HasValue的更方便的方式。

如果你做if(!XmlAttributeName.Equals(null))那麼你將得到一個NullReferenceException如果data == null。這是有趣的,因爲避免這種例外是首要的目標。

if (XmlAttributeName != null && 
XmlAttributeName.All(x => !string.IsNullOrWhiteSpace(x))) 
{ 
    // do here 
}