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
?
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 returnsnull
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With