Search code examples
javaapache-commons-config

Apache Commons Configurations containsKey returns false on existing key


Apologies if this is documented, but I wasn't able to find this on the official documentation.

I'm using XMLConfiguration to load this file, but config.containsKey ("aliases") returns false and config.containsKey ("aliases.alias") returns true. Am I forced to check for "aliases.alias" or is there a way to determine if "aliases" exists as node?

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <name>Vocabulary</name>
    <aliases>
        <alias>Dictionary</alias>
    </aliases>
    <extensions>
        <ext>dic</ext>
        <ext>txt</ext>
        <ext>pdf</ext>
        <ext>doc</ext>
    </extensions>
    <scanmode>1</scanmode>
</configuration>

Solution

  • You can use HierarchicalConfiguration to check the if the node exists or not.

    if(!config.configurationAt("aliases").isEmpty())
    

    containsKey() It is working as expected. public boolean containsKey(String key) Checks if the specified key is contained in this configuration. Note that for this configuration the term "contained" means that the key has an associated value. If there is a node for this key that has no value but children (either defined or undefined), this method will still return FALSE.

    here is code import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration;

    public class HirerarchicalConfig{
    
        public static boolean checkIfNodeExists(String nodeName,XMLConfiguration config){       
            if(!config.configurationAt(nodeName).isEmpty())
                return true;
            else 
                return false;       
        }   
        public static void main(String[] args) throws ConfigurationException{       
    
            XMLConfiguration config = new XMLConfiguration("configFile.xml");
            boolean aliasesNode = checkIfNodeExists("aliases",config);
            System.out.println(aliasesNode);        
        }
    }