Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if XML Element exists

Tags:

c#

xml

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


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.


//if the problem is "just" to verify that the element exist in the xml-file before you //extract the value you could do like this

XmlNodeList YOURTEMPVARIABLE = doc.GetElementsByTagName("YOUR_ELEMENTNAME");

        if (YOURTEMPVARIABLE.Count > 0 )
        {
            doctype = YOURTEMPVARIABLE[0].InnerXml;

        }
        else
        {
            doctype = "";
        }

Not sure what you're wanting to do but using a DTD or schema might be all you need to validate the xml.

Otherwise, if you want to find an element you could use an xpath query to search for a particular element.


How about trying this:

using (XmlTextReader reader = new XmlTextReader(xmlPath))
{
    while (reader.Read())
    {
        if (reader.NodeType == XmlNodeType.Element)
        { 
            //do your code here
        }
    }
}

additionally to sangam code

if (chNode["innerNode"]["innermostNode"]==null)
            return true; //node    *parentNode*/innerNode/innermostNode exists