检查Xml节点是否具有属性

NIl*_*nke 10 c# xml

如何检查节点是否具有特定属性.

我做的是:

string referenceFileName = xmlFileName;
XmlTextReader textReader = new XmlTextReader(referenceFileName);

while (textReader.Read())
{
  XmlNodeType nType = textReader.NodeType;

  // if node type is an element
  if (nType == XmlNodeType.Element)
  {
    if (textReader.Name.Equals("Control"))
    {
      if (textReader.AttributeCount >= 1)
      {
        String val = string.Empty;
        val = textReader.GetAttribute("Visible");
        if (!(val == null || val.Equals(string.Empty)))
        {

        }
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

是否有任何功能来检查给定属性是否存在?

Har*_*san 14

不,我不认为XmlTextReader类中有任何方法可以告诉您特定属性是否存在.

你可以做一件事来检查

if(null == textReader.GetAttribute("Visible"))
{
   //this means attribute doesn't exist
}
Run Code Online (Sandbox Code Playgroud)

因为MSDN说的是GetAttribute方法

    Return the value of the specified attribute. If the attribute is not found,
 a null reference (Nothing in Visual Basic) is returned.
Run Code Online (Sandbox Code Playgroud)


nam*_*ord 8

发现:http://csharpmentor.blogspot.co.uk/2009/05/safely-retrive-attribute-from-xml-node.html

您可以将XmlNode转换为XmlElement,然后使用HasAttribute方法进行检查.我只是尝试了它并且它有效 - 非常有用.

对不起它不是一个使用你的代码的例子 - 我很着急,但希望它有助于未来的问题!

  • 这个答案被严重低估了.这个链接也非常值得一试.+1 (3认同)
  • 我也是+1.它给了我以下构造的想法,在需要字符串的方法调用中使用或者如果属性存在则为空:`(节点为XmlElement).HasAttribute("name2")?node.Attributes ["name2"].Value:String.Empty` (2认同)