xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<configs>
<config>
<key>session-expire-time</key>
<remark>会话超时时间</remark>
<type>input</type>
<default>7200</default>
</config>
<config>
<key>service-record-enable</key>
<remark>服务调用日志</remark>
<type>switch</type>
<default>true</default>
</config>
</configs>
代码实现
public static void load() throws IOException {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
InputStream inputStream = null;
try {
ClassPathResource resource = new ClassPathResource("config.xml");
inputStream = resource.getInputStream();
builder = dbf.newDocumentBuilder();
doc = builder.parse(inputStream);
NodeList configs = doc.getChildNodes().item(0).getChildNodes();
for (int i = 0; i < configs.getLength(); i++) {
Node item = configs.item(i);
if ("config".equals(item.getNodeName())) {
NodeList items = item.getChildNodes();
for (int k = 0; k < items.getLength(); k++) {
Node node = items.item(k);
if ("key".equals(node.getNodeName())) {
System.out.println(node.getTextContent());
} else if ("remark".equals(node.getNodeName())) {
System.out.println(node.getTextContent());
} else if ("default".equals(node.getNodeName())) {
System.out.println(node.getTextContent());
} else if ("type".equals(node.getNodeName())) {
System.out.println(node.getTextContent());
}
}
}
}
} catch (Exception e) {
throw new RuntimeException("读取配置文件信息失败");
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}