2011-11-16 130 views
16

我在MSDN上檢查XmlNode.Attributes topic關於檢查一個XmlNode屬性是否存在給定名稱的方法。那麼,沒有關於如何檢查項目的示例。如何檢查XmlAttributeCollection中是否存在屬性?

我有類似:

//some code here... 

    foreach (XmlNode node in n.SelectNodes("Cities/City")) 
    { 
     //is there some method to check an attribute like 
     bool isCapital = node.Attributes.Exist("IsCapital"); 

     //some code here... 
    } 

那麼,什麼是最好的方法來檢查,如果一個屬性在每個節點存在與否? 可以使用node.Attribute["IsCapital"]!=null

回答

32

只需使用索引 - 如果屬性不存在,索引器返回null

bool isCapital = nodes.Attributes["IsCapital"] != null; 

這是記錄在XmlAttributeCollection.ItemOfProperty (String)

XmlAttribute與指定的名稱。如果該屬性不存在,則此屬性返回null

+0

@JuniorMayhé - Obrigado! – Oded

+0

+1,用於真棒捕捉。 –

+0

似乎不適用於可以存在但沒有指定值的布爾屬性。像'' – Ivan