java DOM4J 无限连解析XML

/**
 * 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 block
			e.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);
			}

		}

	}

	@Test
	public 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));
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值