码迷,mamicode.com
首页 > 其他好文 > 详细

dom4j解析xml中指定元素下内容

时间:2015-06-04 15:46:57      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:dom4j

需求:XML为如下样式,现在我只想取得timer下面的5000和60000.

解决办法如下:

<?xml version="1.0" encoding="UTF-8"?>
<we>
	
	<message id="1001">
		<String>Id</String>
		<String>name</String>
		<String>sfz</String>
		<String>w</String>
	</message>
	<!-- 定时任务设置 -->
	<timer>
		<delay>5000</delay>
		<period>60000</period>
	</timer>
</we>

/**
	 * 解析指定xml路径下的信息
	 * 
	 * @param fileName
	 *            xml文件路径
	 * @param xmlPath
	 *            xml里元素路径
	 * @return 返回map,如map.get("delay")就可取到下面的5000
	 * <timer>
		<delay>5000</delay>
		<period>60000</period>
	   </timer>
	 */
	public Map parserXml(String fileName, String xmlPath) {
		Document document;
		Map map = new HashMap();
		try {
			document = getDocument(fileName);
			List list = document.selectNodes(xmlPath);
			for (int i = 0; i < list.size(); i++) {
				Element timer = (Element) list.get(i);
				for(Iterator j = timer.elementIterator();j.hasNext();){
					Element node = (Element) j.next();
					//System.out.println(node.getName() + ":" + node.getText());
					map.put(node.getName(), node.getText());
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return map;
	}

	private Document getDocument(String xmlFile) throws DocumentException {
		SAXReader reader = new SAXReader();
		return reader.read(xmlFile);
	}

public static void main(String[] args) {
		Dom4jDemo d = new Dom4jDemo();
		String relativelyPath = new File(Dom4jDemo.class.getResource("/")
				.getPath()).getParent() + File.separator + "src\\sysConfig.xml";
		System.out.println(relativelyPath);
		// d.createXml(relativelyPath);
		/*List list = d.parserXml(relativelyPath);
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i));
		}*/
		String xmlPath = "/we/timer";
		Map map = d.parserXml(relativelyPath, xmlPath);
		System.out.println(map.get("delay"));

	}


dom4j解析xml中指定元素下内容

标签:dom4j

原文地址:http://blog.csdn.net/xiongwt/article/details/46361489

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!