java DOM4J 无限连解析XML

来源:互联网 发布:lol冰狼辅助源码 编辑:程序博客网 时间:2024/05/02 05:00
/** * RecursiveWholeXMLUtil.java * com.hao947.XMLUtil *  * Function: TODO *  * ver date author * ────────────────────────────────── * 2014-2-5 雪藏的心 *  * Copyright (c) 2014, inspurworld All Rights Reserved. */package com.hao947.XMLUtil;import java.io.File;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import org.dom4j.Attribute;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;import org.junit.Test;/** * ClassName:RecursiveWholeXMLUtil * Function: TODO ADD FUNCTION * Reason: TODO ADD REASON *  * @author 雪藏的心 * @version * @since Ver 1.1 * @Date 2014-2-5 下午3:34:06 *  * @see * @deprecated */public class RecursiveWholeXMLUtil {public static List<Map<String, String>> RecursiveWholeXML(String filename) {List<Map<String, String>> list = new ArrayList<Map<String, String>>();SAXReader saxReader = new SAXReader();try {Document document = saxReader.read(new File(filename));Element root = document.getRootElement();// 递归recursiveNode(root, list);return list;}catch (DocumentException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}/** * recursive Node:(递归遍历所有的节点获得对应的值) *  * @param @param root * @param @param list 设定文件 * @return void DOM对象 * @throws * @since CodingExample Ver 1.1 */private static void recursiveNode(Element root ,        List<Map<String, String>> list) {// 遍历根节点的所有孩子节点for (Iterator iter = root.elementIterator(); iter.hasNext();) {HashMap<String, String> map = new HashMap<String, String>();Element element = (Element) iter.next();if (element == null)continue;// 获取属性和它的值for (Iterator attrs = element.attributeIterator(); attrs.hasNext();) {Attribute attr = (Attribute) attrs.next();if (attr == null)continue;String attrName = attr.getName();String attrValue = attr.getValue();map.put(attrName, attrValue);}// 如果有PCDATA,则直接提出if (element.isTextOnly()) {String innerName = element.getName();String innerValue = element.getText();map.put(innerName, innerValue);list.add(map);}else {list.add(map);// 递归调用recursiveNode(element, list);}}}@Testpublic void show() {String filename = "src\\users.xml";List<Map<String, String>> list = RecursiveWholeXMLUtil        .RecursiveWholeXML(filename);for (Map<String, String> map : list) {for (String ss : map.keySet()) {System.out.println(ss + ":" + map.get(ss));}}}}

0 0
原创粉丝点击