dom4j解析xml

package com.ydq.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Dom4j {

	/**
	 * @description 將xml字符串轉換成map,
	 * @param xml
	 * @param type
	 *            0:格式保持遞歸,1:只有取值模式
	 * @return Map
	 * @throws DocumentException
	 */
	public static Map<String, Object> readStringXmlOut(String xml, int type)
			throws DocumentException {
		Document doc = null;
		doc = DocumentHelper.parseText(xml);
		Element element = doc.getRootElement();
		Map<String, Object> getChildrenMap = getChildrenMap(element, type);
		Map<String, Object> map = new HashMap<String, Object>();
		if (null == getChildrenMap) {
			map.put(element.getName(), element.getTextTrim());
		} else {
			if (0 == type) {
				map.put(element.getName(), getChildrenMap);
			} else if (1 == type) {
				map.putAll(getChildrenMap);
			}
		}
		return map;
	}

	/**
	 * 遞歸解析子元素
	 * 
	 * @param element
	 * @param type
	 *            0:格式保持遞歸,1:只有取值模式
	 * @return
	 */
	private static Map<String, Object> getChildrenMap(Element element, int type) {

		List<Element> childrenList = element.elements();
		if (childrenList.isEmpty()) {
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>(
				childrenList.size());
		for (Element childrenElement : childrenList) {
			Map<String, Object> map2 = getChildrenMap(childrenElement, type);
			if (null == map2) {
				map.put(childrenElement.getName(),
						childrenElement.getTextTrim());
			} else {
				if (0 == type) {
					map.put(childrenElement.getName(),
							getChildrenMap(childrenElement, type));
				} else if (1 == type) {
					map.putAll(getChildrenMap(childrenElement, type));
				}
			}
		}
		return map;
	}

	public static void main(String[] args) throws DocumentException {

		String xmlString = "<xml><appid>wx2421b1c4370ec43b</appid><attach>支付測試</attach><body>JSAPI支付測試</body><mch_id>10000100</mch_id><nonce_str>1add1a30ac87aa2db72f57a2375d8fec</nonce_str><notify_url>http://wxpay.weixin.qq.com/pub_v2/pay/notify.v2.php</notify_url><openid>oUpF8uMuAJO_M2pxb1Q9zNjWeS6o</openid><out_trade_no>1415659990</out_trade_no><spbill_create_ip>14.23.150.211</spbill_create_ip><total_fee>1</total_fee><trade_type>JSAPI</trade_type><sign>0CB01533B8C1EF103065174F50BCA001</sign></xml>";
		System.out.println(xmlString);
		System.out.println(readStringXmlOut(xmlString, 1));
		System.out.println(readStringXmlOut(xmlString, 0));
	}

}
相關文章
相關標籤/搜索