1

我的目标是 java 1.5 我有一个从另一个软件提供商提供的自定义配置文件,我需要阅读它

<?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>

我需要把它放在一个哈希映射中并作为访问它。

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

我认为我可以在 HashMap 中加载信息,我可以使用 DEFAULT.LOGGER_NAME 之类的键访问

我可以使用 APACHE COMMONS 配置(如何?)还是太复杂而使用 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);

                }
            }

并添加两个方法在这种情况下,我使用变量命名空间而不是环境

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 回答