Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Xml Node has an Attribute

Tags:

c#

xml

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?

like image 960
NIlesh Lanke Avatar asked Dec 13 '11 12:12

NIlesh Lanke


3 Answers

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.
like image 130
Haris Hasan Avatar answered Oct 19 '22 11:10

Haris Hasan


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!

like image 43
namford Avatar answered Oct 19 '22 10:10

namford


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();
like image 25
sll Avatar answered Oct 19 '22 09:10

sll