java-读取xml

java:

@Override
    public Map<String, Object> getCommunityCountByRegion(String regionCode) {
        Map<String,Object> map = new HashMap<>();
        try {
            URL url = getClass().getClassLoader().getResource("community-count.xml");
            File file = new File(url.toURI());
            logger.info("community-count.xml,URL:" + file.getPath());
            SAXReader reader = new SAXReader();
            Document doc = reader.read(file);
            Element root = doc.getRootElement();
            Iterator<?> listItr = root.elementIterator("region");
            while (listItr.hasNext()){
                Element regionNode = (Element) listItr.next();
                if (regionCode.equals(regionNode.attribute("code").getValue())){
                    map.put("communityTotal",regionNode.element("community-total").getTextTrim());
                    map.put("communityComplete",regionNode.element("community-complete").getTextTrim());
                    map.put("villageTotal",regionNode.element("village-total").getTextTrim());
                    map.put("villageComplete",regionNode.element("village-complete").getTextTrim());
                }
            }
        } catch (Exception e) {
            logger.error("getCommunityCountByRegion error: ",e);
        }
        return map;
    }

xml:

<?xml version="1.0" encoding="UTF-8"?>
<list>
    <region name = "XX市" code = "4101">
        <community-total>132</community-total>
        <village-total>68</village-total>
        <community-complete>10</community-complete>
        <village-complete>5</village-complete>
    </region>
    <region name = "XX县" code = "410602">
        <community-total>60</community-total>
        <village-total>8</village-total>
        <community-complete>2</community-complete>
        <village-complete>10</village-complete>
    </region>
</list>
原文地址:https://www.cnblogs.com/lijianda/p/13895068.html