1

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?

4

1 に答える 1

1

短い構成ファイルの最適な解決策は、ハッシュ マップを作成することです。

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

                }
            }

2 つのメソッドを追加します。この場合、環境の代わりに変数の名前空間を使用します。

1) この場合

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);
    }
于 2013-10-07T06:01:08.317 に答える