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="" +
"" +
"" +
" " +
"" +
" " +
" " +
" ";
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 = newByteArrayInputStream(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 = https://www.it610.com/article/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();
}}
推荐阅读
- Integer常量池结合源码解析
- Java基础|Java 打印空心等腰三角形(方法2)
- gradle 每次运行都会下载依赖的解决办法
- 使用vector代替数组
- 如何获取ResultSet的行数和列数
- XML|xml 解析成map
- Java 时间戳格式化
- Java基础|Android开发——JVM、Dalvik以及ART的区别
- Java 8 时间,字符串和Long时间戳互转