JavaReadXML

xml文件内容

<?xml version="1.0" encoding="UTF-8"?>
<ip_type>
    <ip name="办公网(非行软)">192.168.75.168</ip>
    <ip name="办公网">192.168.75.167</ip>
    <ip name="研发网">192.168.102.168</ip>
</ip_type>

Java文件内容

package com.iflytek.web.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class NetworkUtil {    
    public static Map<String, String> network_map = new HashMap<String, String>();

    private NetworkUtil() {
        //读取XML文件,获得document对象
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(new File("resources/com/iflytek/resources/system/network.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        Element node = document.getRootElement();//获取根节点
        List node1 = node.elements("ip");//获取根节点下所有元素名为“ip”的元素
        Map<String, String> map = new HashMap<String, String>();//汉字作为key,ip地址作为value

        for (Iterator it = node1.iterator(); it.hasNext();) {
            Element elm = (Element) it.next();
            map.put(elm.attributeValue("name"), elm.getText());
        }
        network_map = map;
    }

    private static final NetworkUtil networkUtil = new NetworkUtil(); 

    public static NetworkUtil getInstance(){        
        return networkUtil;
    }
}

你可能感兴趣的:(java,xml)