Check if XML Element exists

后端 未结 13 1660
傲寒
傲寒 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: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;
    }
    

提交回复
热议问题