[c#] 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.

This question is related to c# xml

The answer is


Just came across the same problem and the null-coalescing operator with SelectSingleNode worked a treat, assigning null with string.Empty

 foreach (XmlNode txElement in txElements)
 {
     var txStatus = txElement.SelectSingleNode(".//ns:TxSts", nsmgr).InnerText ?? string.Empty;
     var endToEndId = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty;
     var paymentAmount = txElement.SelectSingleNode(".//ns:InstdAmt", nsmgr).InnerText ?? string.Empty;
     var paymentAmountCcy = txElement.SelectSingleNode(".//ns:InstdAmt", nsmgr).Attributes["Ccy"].Value ?? string.Empty;
     var clientId = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty;
     var bankSortCode = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty; 

     //TODO finish Object creation and Upsert DB
  }

You can validate that and much more by using an XML schema language, like XSD.

If you mean conditionally, within code, then XPath is worth a look as well.


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.


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


A little bit late, but if it helps, this works for me...

XmlNodeList NodoEstudios = DocumentoXML.SelectNodes("//ALUMNOS/ALUMNO[@id=\"" + Id + "\"]/estudios");

string Proyecto = "";

foreach(XmlElement ElementoProyecto in NodoEstudios)
{
    XmlNodeList EleProyecto = ElementoProyecto.GetElementsByTagName("proyecto");
    Proyecto = (EleProyecto[0] == null)?"": EleProyecto[0].InnerText;
}

Following is a simple function to check if a particular node is present or not in the xml file.

public boolean envParamExists(String xmlFilePath, String paramName){
    try{
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(xmlFilePath));
        doc.getDocumentElement().normalize();
        if(doc.getElementsByTagName(paramName).getLength()>0)
            return true;
        else
            return false;
    }catch (Exception e) {
        //error handling
    }
    return false;
}

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

 string name = "some node name";
    var xDoc = XDocument.Load("yourFile");
    var docRoot = xDoc.Element("your docs root name");

     var aNode = docRoot.Elements().Where(x => x.Name == name).FirstOrDefault();
                if (aNode == null)
                {
                    return $"file has no {name}";
                }

//I am finding childnode ERNO at 2nd but last place

If StrComp(xmlnode(i).ChildNodes.Item(xmlnode(i).ChildNodes.Count - 1).Name.ToString(), "ERNO", CompareMethod.Text) = 0 Then
                xmlnode(i).ChildNodes.Item(xmlnode(i).ChildNodes.Count - 1).InnerText = c
            Else
                elem = xmldoc.CreateElement("ERNo")
                elem.InnerText = c.ToString
                root.ChildNodes(i).AppendChild(elem)
            End If

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.


//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");                
                }
            }     

//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 = "";
        }