短配置文件的最佳解决方案是构建哈希映射。
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);
}