java--dom读取xml文件

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>

你可能感兴趣的:(java--dom读取xml文件)