需求: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")); }
时间: 2024-10-16 05:49:23