检查Xml节点是否具有属性

时间:2011-12-13 12:12:58

标签: 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)))
        {

        }
      }
    }
  }

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

6 个答案:

答案 0 :(得分:14)

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

你可以做一件事来检查

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

因为MSDN说的是GetAttribute方法

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

答案 1 :(得分:8)

找到了这个:http://csharpmentor.blogspot.co.uk/2009/05/safely-retrive-attribute-from-xml-node.html

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

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

答案 2 :(得分:2)

尝试使用LINQ-To-XML(下面的查询可能需要一些小修复,因为我没有使用XML)

XDocument xdoc = XDocument.Load("Testxml.xml");  

// It might be that Control element is a bit deeper in XML document
// hierarchy so if you was not able get it work please provide XML you are using
string value = xdoc.Descendants("Control")
                  .Where(d => d.HasAttributes
                              && d.Attribute("Visible") != null
                              && !String.IsNullOrEmpty(d.Attribute("Visible").Value))
                  .Select(d => d.Attribute("Visible").Value)
                  .Single();

答案 3 :(得分:0)

//使用XmlReader检查xml元素值是否存在

      using (XmlReader xmlReader = XmlReader.Create(new StringReader("XMLSTRING")))
       {

           if (xmlReader.ReadToFollowing("XMLNODE")) 

            {
                string nodeValue = xmlReader.ReadElementString("XMLNODE");                
            }
        }     

答案 4 :(得分:0)

参考Harish的回答,以下代码为我工作

 XmlTextReader obj =new XmlTextReader("your path");
    //include @before"" if its local path
      while (obj.Read()) { 
      Console.WriteLine(obj.GetAttribute("name"));
      obj.MoveToNextAttribute();
      }

答案 5 :(得分:0)

如果有人不使用阅读器而只是使用XmlDocument,请尝试使用XmlAttributeCollection / XmlAttribute

XmlDocument doc = new XmlDocument();
try{
doc.Load(_indexFile);
    foreach(XmlNode node in doc.DocumentElement.ChildNodes){
        XmlAttributeCollection attrs = node.Attributes;
        foreach(XmlAttribute attr in attrs){
            Console.WriteLine(node.InnerText + ": " + attr.Name + " - " + attr.Value);
            if(attr.Name == "my-amazing-attribute")
            {
                //Do something with attribute
            }
        }
    }
}
} catch (Exception ex) {
    //Do something with ex
}
相关问题