xml报文转map

XML报文转Map
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class StringXmlToMap {

/**
 * @param args
 * @throws JDOMException 
 * @throws IOException 
 */
public static void main(String[] args) throws IOException, JDOMException {
	//待转化的String类型的xml报文
	String strxml="<xml>" +
						"<return_code>" +
							"<![CDATA[FAIL]]>" +
						"</return_code>" +
						"<return_msg>" +
						"	<![CDATA[appid不存在]]>" +
						"</return_msg>" +
					"</xml>";
	
	StringXmlToMap str=new StringXmlToMap();
	Map map=str.strXmlToMap(strxml);
	System.out.println(map.get("return_code"));
	

}

/**
 * 将传入的 String 类型的XML报文转化为Map类型的对象
 * @param strxml
 * @return
 * @throws IOException
 * @throws JDOMException
 */
public Map strXmlToMap(String strxml) throws IOException, JDOMException{
	
	if(null == strxml || "".equals(strxml)) {
		return null;
	}
	
	Map m = new HashMap();
	InputStream in = new   ByteArrayInputStream(strxml.getBytes("UTF-8"));  
	SAXBuilder builder = new SAXBuilder();
	Document doc = builder.build(in);
	Element root = doc.getRootElement();
	List list = root.getChildren();
	Iterator it = list.iterator();
	while(it.hasNext()) {
		Element e = (Element) it.next();
		String k = e.getName();
		String v = "";
		List children = e.getChildren();
		if(children.isEmpty()) {
			v = e.getTextNormalize();
		} else {
			v = getChildrenText(children);
		}
		
		m.put(k, v);
	}
	
	//关闭流
	in.close();
	
	return m;
}

/**
 * 获取子节点的Xml
 * @param children
 * @return
 */
public static String getChildrenText(List children) {
	StringBuffer sb = new StringBuffer();
	if(!children.isEmpty()) {
		Iterator it = children.iterator();
		while(it.hasNext()) {
			Element e = (Element) it.next();
			String name = e.getName();
			String value = e.getTextNormalize();
			List list = e.getChildren();
			sb.append("<" + name + ">");
			if(!list.isEmpty()) {
				sb.append(getChildrenText(list));
			}
			sb.append(value);
			sb.append("</" + name + ">");
		}
	}
	
	return sb.toString();
}

}

原文链接:https://blog.csdn.net/bestcxx/article/details/50312765

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值