Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an attribute exist in XmlAttributeCollection?

Tags:

I was checking XmlNode.Attributes topic on MSDN about methods for checking if a XmlNode an attribute exists given its name. Well, there is no sample on how to check an item.

I have something like:

  //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...   } 

So, what would be the best approach to check if an attribute exist or not in each node? Is it ok to use node.Attribute["IsCapital"]!=null ?

like image 627
Junior Mayhé Avatar asked Nov 16 '11 13:11

Junior Mayhé


1 Answers

Just use the indexer - if the attribute doesn't exist, the indexer returns null:

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

This is documented on XmlAttributeCollection.ItemOfProperty (String).

The XmlAttribute with the specified name. If the attribute does not exist, this property returns null.

like image 69
Oded Avatar answered Nov 19 '22 15:11

Oded