11

How do I check if a node has particular attribute or not.

What I did is:

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)))
        {

        }
      }
    }
  }

Is there any function to check that a given attribute is present or not?

1
  • 3
    The word is "check", not "chk". Commented Dec 13, 2011 at 12:16

6 Answers 6

17

No, I don't think there is any method in XmlTextReader class which can tell you whether a particular attribute exists or not.

You can do one thing to check

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

because MSDN says about GetAttribute method

    Return the value of the specified attribute. If the attribute is not found,
 a null reference (Nothing in Visual Basic) is returned.
Sign up to request clarification or add additional context in comments.

3 Comments

Will you suggeset any other class which has method to check whether a particular attribute exists or not.
Not in my knowledge. I don't know any method which returns bool value about whether the attribute exists or not. All I know returns null if attribute doesn't exist
As MSDN says: "Starting with the .NET Framework 2.0, we recommend that you use the XmlReader class instead."
9

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

You can convert the XmlNode to an XmlElement then use the HasAttribute method to check. I just tried it and it works - very useful.

Sorry its not an example using your code - I'm in a hurry but hope it helps future askers!

2 Comments

This answer is grossly underrated. This link is also well worth checking out. +1
+1 from me, too. It gave me the idea of the following construct to use in a method-call that needs the string or empty if the attribute exists: (node as XmlElement).HasAttribute("name2") ? node.Attributes["name2"].Value : String.Empty
2

Try out LINQ-To-XML (query below might require minor fixes since I'm not have XML you are using)

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();

Comments

0

//Check xml element value if exists using XmlReader

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

           if (xmlReader.ReadToFollowing("XMLNODE")) 

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

Comments

0

Taking refernce from Harish's answer,following code worked for me

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

Comments

0

If anyone is not using a reader and just an XmlDocument try 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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.