java读取xml文件

1、现在resources目录下创建xml文件:

-resources

--config

---shipCorp.xml

 

shipCorp.xml:文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<shipCorp>
    <ship code="TLC" name="泉洲太豪"></ship>
    <ship code="POS" name="埔洋船务"></ship>
    <ship code="COSCO" name="中远"></ship>
    <ship code="CSCO" name="中海"></ship>
    <ship code="NQGS" name="南青"></ship>
    <ship code="COH" name="京汉"></ship>
    <ship code="DBR" name="大连环渤海"></ship>
    <ship code="HY" name="红运实业"></ship>
    <ship code="ZIM" name="以星轮船"></ship>
</shipCorp>

2、新建工具类:

package com.portx.util;

import org.apache.commons.collections.CollectionUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.util.*;

/**
 * 品xml文件生成和解析
 * Created by gmq on 2016/5/27.
 */
public class XmlReaderUtil {

    private static final Logger log = LoggerFactory.getLogger(XmlReaderUtil.class);

    private static List<Map<String, Object>> result = new ArrayList<>();

    private static String PLATE_SHIP_CORP = "shipCorp.xml";

    private static int LENGTH = PLATE_SHIP_CORP.length() - 4;

    /**
     * 获得全部的船公司
     *
     * @return
     */
    public static List<Map<String, Object>> getAllShips() {
        isResultEmpty();

        return result;
    }

    /**
     * 根据船公司code获得船公司名
     *
     * @param key
     * @return
     */
    public static String getValueByKey(String key) {
        if (StringUtil.isEmpty(key)) {
            return "";
        }

        isResultEmpty();

        String value = "";
        Map<String, Object> map = null;
        for (int i = 0; i < result.size(); i++) {
            map = result.get(i);
            if (map.containsKey(key)) {
                value = String.valueOf(map.get(key));
                break;
            }
        }

        return value;
    }

    private static void isResultEmpty() {
        if (CollectionUtils.isEmpty(result)) {
            assembleShipCorpMap(PLATE_SHIP_CORP);
        }
    }

    private static void assembleShipCorpMap(String file) {
        Document document = reader(file);
        Set set = null;
        Element root = document.getRootElement();
        List<Element> childElements = root.elements();

        Map<String, Object> map = null;

        for (Element child : childElements) {
            map = new HashMap<>();
//            set = new HashSet();
//            List<Element> childList = child.elements();
//            for (Element element : childList)
//            {
//                set.add(element.getText());
//            }
            map.put(child.attributeValue("code"), child.attributeValue("name"));
            result.add(map);
        }
    }


    private static Document reader(String file) {
        Document document = null;
        log.info("Class Root Directory::" + 111);
        URL url = XmlReaderUtil.class.getResource("/config/" + file);
        log.info("板品种xml文件路径:: " + file);

        InputStream inputStream = null;

        try {
            try {
                inputStream = new FileInputStream(new File(url.getPath()));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            SAXReader reader = new SAXReader();
            try {
                document = reader.read(inputStream);
            } catch (DocumentException de) {
                log.error("Document对象操作异常");
                de.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.error("流关闭异常");
                e.printStackTrace();
            }
        }

        return document;
    }

    public static void main(String[] args) {
//        List<Map<String, Object>> list = XmlReaderUtil.getAllShips();
//        System.out.println(list);
    }
}

以上就可以了。

 

posted @ 2016-05-27 13:25  园芳宝贝  阅读(754)  评论(0编辑  收藏  举报