Check if XML Element exists

Viewed 172974

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.

13 Answers
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

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.

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.

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;
}

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
  }
 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
Related