简体   繁体   English

如何检查XmlAttributeCollection中是否存在属性?

[英]How can I check if an attribute exist in XmlAttributeCollection?

I was checking XmlNode.Attributes topic on MSDN about methods for checking if a XmlNode an attribute exists given its name. 我在MSDN上检查XmlNode.Attributes主题有关检查XmlNode属性是否存在的方法。 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 ? 是否可以使用node.Attribute["IsCapital"]!=null

Just use the indexer - if the attribute doesn't exist, the indexer returns null : 只需使用索引器 - 如果该属性不存在,索引器将返回null

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

This is documented on XmlAttributeCollection.ItemOfProperty (String) . 这在XmlAttributeCollection.ItemOfProperty (String)

The XmlAttribute with the specified name. 具有指定名称的XmlAttribute If the attribute does not exist, this property returns null . 如果该属性不存在,则此属性返回null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM