0

I am trying to check if node "DEF" exists in my xml file

My xml file looks like this:

<Struct>
   <A>
      <ABC>
      </ABC>
      <DEF>
      </DEF>
   </A>
   <B>
      <GHI>
      </GHI>
   </B>
</Struct>

And my code looks like this:

XmlDocument stru = new XmlDocument();
stru.Load(path + "Structure.xml");
if (stru.ChildNodes[0].HasChildNodes)
{
    for (int i = 0; i < stru.ChildNodes[0].ChildNodes.Count; i++)
    {
        if (stru.ChildNodes[0].ChildNodes[i].Attributes["DEF"] != null)
        {
            enabled = true;
            break;
        }
        else
        {
            MessageBox.Show("no");
        }

    }
}
else { MessageBox.Show("Error!"); }

And it immediately shows messagebox with "Error!" in it

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Ivan Ivanov
  • 3
  • 1
  • 5

1 Answers1

3

Use linq to xml with Descendants:

Returns a filtered collection of the descendant elements for this document or element, in document order. Only elements that have a matching XName are included in the collection.(Inherited from XContainer.)

var abcs = XDocument.Load("data.xml").Descendants("ABC");
if(abcs.Any())
{
    // There is at least one element of "ABC"
}
Gilad Green
  • 36,708
  • 7
  • 61
  • 95