Question

Check if XML Element exists

How can someone validate that a specific element exists in an XML file? Say I have an ever changing XML file and I need to verify every element exists before reading/parsing it.

 47  189811  47
1 Jan 1970

Solution

 71
if(doc.SelectSingleNode("//mynode")==null)....

Should do it (where doc is your XmlDocument object, obviously)

Alternatively you could use an XSD and validate against that

2008-09-19

Solution

 6

You can iterate through each and every node and see if a node exists.

doc.Load(xmlPath);
        XmlNodeList node = doc.SelectNodes("//Nodes/Node");
        foreach (XmlNode chNode in node)
        {
            try{
            if (chNode["innerNode"]==null)
                return true; //node exists
            //if ... check for any other nodes you need to
            }catch(Exception e){return false; //some node doesn't exists.}
        }

You iterate through every Node elements under Nodes (say this is root) and check to see if node named 'innerNode' (add others if you need) exists. try..catch is because I suspect this will throw popular 'object reference not set' error if the node does not exist.

2011-07-11