现在的位置: 首页 > 综合 > 正文

根据node属性解析xml 并存入map中

2013年03月05日 ⁄ 综合 ⁄ 共 1362字 ⁄ 字号 评论关闭

xml文件:user.xml

<?xml version="1.0" encoding="UTF-8"?>
<MonitConfig>
	<Monits>
		<moint name="calLog" path="E:/jgcal.log"></moint>
		<moint name="gatewayLog" path="E:/jgcal.log"></moint>
	</Monits>
</MonitConfig>

实现类

public class LoadPathConfig {
	/**
	 * 解析配置文件
	 * 
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	private static Map parserXml(String fileName) throws Exception {
		List ruleList = new ArrayList();
		Map map = new HashMap();
		try {
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(fileName);
			Element monitConfig = document.getRootElement();// 获取根节点
			for (Iterator i = monitConfig.elementIterator(); i.hasNext();) {
				Element monits = (Element) i.next();
				if ("Monits".equals(monits.getName())) {
					for (Iterator j = monits.elementIterator(); j.hasNext();) {
						Element moint = (Element) j.next();
						if ("moint".equals(moint.getName())) {
							String key = moint.attribute("name").getValue();
							String value = moint.attribute("path").getValue();
							map.put(key, value);
						}
					}
				}
			}
		} catch (DocumentException e) {
			String message = "解析配置文件异常";
			throw new Exception(message, e);
		}
		return map;
	}

	public static void main(String[] args) {
		LoadPathConfig l=new LoadPathConfig();
		String path=System.getProperty("user.dir")+"/src/config/user.xml";
		Map map;
		try {
			map = l.parserXml(path);
			Iterator it=map.keySet().iterator();
			while(it.hasNext()){
				String key=(String)it.next();
				System.out.println(key);
				System.out.println(map.get(key));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

注:导入dom4j.jar

抱歉!评论已关闭.