java--dom讀取xml文件
public Map readXml() {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc;
InputStream stream = this.getClass().getResourceAsStream("/dictionaries.xml");
doc = builder.parse(stream);
Element root = doc.getDocumentElement();
NodeList list = root.getElementsByTagName("dictionary");
Map map = new LinkedHashMap();
ArrayList<String> types = new ArrayList<String>();
for (int i = 0; i < list.getLength(); i++) {
String key = list.item(i).getAttributes().getNamedItem("name").getNodeValue();
String value = list.item(i).getAttributes().getNamedItem("value").getNodeValue();
map.put(key, value);
}
return map;
} catch (Exception ex) {
return null;
}
}
dictionaries.xml文件如下:<?xml version="1.0" encoding="UTF-8"?>
<dictionaries>
<dictionary name="項目類型" value="project.types" />
<dictionary name="項目狀態" value="project.statuses" />
<dictionary name="任務階段" value="task.stages" />
<dictionary name="任務狀態" value="task.statuses" />
<dictionary name="發生幾率" value="risk.probability" />
<dictionary name="危險程度" value="risk.harm" />
<dictionary name="風險狀態" value="risk.status" />
<dictionary name="預案類別" value="risk.type" />
<dictionary name="合同類型" value="contract.type" />
<dictionary name="合同狀態" value="contract.status" />
</dictionaries>