Question

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 ?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top