21

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 ?

Junior Mayhé
  • 16,144
  • 26
  • 115
  • 161

1 Answers1

43

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.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • Seems inapplicable for boolean attributes which can be present but have no value specified. like `` – Ivan Jun 22 '13 at 21:10
  • 1
    @Ivan - you seem to be thinking about HTML, not XML. XML does not allow attributes that do not have values in them. – Oded Jun 22 '13 at 21:12
  • But what about XHTML, @Oded? Isn't it meant to be valid XML while allowing attributes without values for booleans? I actually seek to use this in my own XML for "debloat" purpose. – Ivan Jun 22 '13 at 21:32
  • @Ivan - No. XHTML has to be valid XML too - that's the whole point of it. It doesn't allow boolean attributes. – Oded Jun 22 '13 at 21:41
  • For practical use, keep in mind that `XmlNode.Attributes` property can be null. `nodes?.Attributes["IsCapital"] != null` – Arin Taylor Feb 08 '17 at 16:37