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

需求: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"));

	}


原文地址:https://www.cnblogs.com/mengfanrong/p/5101106.html