Parsing custom xml config file

1.5k views Asked by At

My target is java 1.5 I have a custom configuration file provided from another software provider i need to read it

<?xml version="1.0" encoding="ISO-8859-1"?>
<environments>
    <environment key="DEFAULT" description="Default">
        <variable name="LOGGER_NAME" value="LCI"/>
        <variable name="MAIL_SERVER" value="127.0.0.1"/>
            ......
    </environment>
    <environment key="TEST" description="Test">
        <variable name="LOGGER_NAME" value="LCO"/>
        <variable name="MAIL_SERVER" value="192.168.2.15"/>
            ......
    </environment>
</environments>

I need to put it in a hash map and acces to it as.

MyPropertyManager.getProperty("DEFAULT","LOGGER_NAME")

I think that I can load infos in a HashMap where I can acces usingg key like DEFAULT.LOGGER_NAME

Can I use APACHE COMMONS Configuration (HOW?) or is too complex and is better to use Xpath?

1

There are 1 answers

0
user1594895 On BEST ANSWER

The best solution for short config files is to build hash map.

XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression expr1 = xpath.compile("/environments/environment");
            XPathExpression expr2 = xpath.compile("@key");
            XPathExpression expr12 = xpath.compile("variable");
            XPathExpression expr121 = xpath.compile("@name");
            XPathExpression expr122 = xpath.compile("@value");

            NodeList environmentNL = (NodeList) expr1.evaluate(doc, XPathConstants.NODESET);
            for (int i = 0; i < environmentNL.getLength(); i++) {
                Node environmentI = environmentNL.item(i);
                String envKey =  (String) expr2.evaluate(environmentI, XPathConstants.STRING);


                NodeList variableNL = (NodeList) expr12.evaluate(environmentI, XPathConstants.NODESET);
                for (int j = 0; j < variableNL.getLength(); j++) {
                    Node variableI = variableNL.item(j);
                    String valueName =  (String) expr121.evaluate(variableI, XPathConstants.STRING);
                    String valueValue =  (String) expr122.evaluate(variableI, XPathConstants.STRING);

                    val.put(envKey+"."+valueName, valueValue);

                }
            }

And add two methods In this case I use the variable namespace instead environment

1) In this case

public static String getProperties(String namespace, String value) throws ConfigLoaderException {
        String param=namespace+"."+value;

        if(!val.containsKey(param)){
            throw new ConfigLoaderException(param+" ERROR");
        }else{
            return val.get(param);

        }
    }

...

public static String getProperties(String value) throws ConfigLoaderException {
        String namespace="DEFAULT";
        return getProperties(namespace,value);
    }