Check if XML Element exists

后端 未结 13 1553
傲寒
傲寒 2020-12-03 06:20

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

相关标签:
13条回答
  • 2020-12-03 07:10
     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}";
                    }
    
    0 讨论(0)
  • 2020-12-03 07:13

    //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 = "";
            }
    
    0 讨论(0)
  • 2020-12-03 07:14

    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.

    0 讨论(0)
  • 2020-12-03 07:14

    additionally to sangam code

    if (chNode["innerNode"]["innermostNode"]==null)
                return true; //node    *parentNode*/innerNode/innermostNode exists
    
    0 讨论(0)
  • 2020-12-03 07:14

    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;
    }
    
    0 讨论(0)
  • 2020-12-03 07:15

    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.

    0 讨论(0)
提交回复
热议问题