此工具类是把xml文件转换成map的形式。其实dom4j和jdom都是可以做的。
/**
* 2017年10月19日下午11:35:09
*/
package com.jjmc.dcl.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
*
* @author huangtao
* 2017年10月19日下午11:35:09
* dclTask
* @parameter
* TODO
* 解析xml
*/
public class XmlUtil {
//日志
private static final StringDEBUG_PREFIX = "[XmlUtil]";
private static final StringINFO_PREFIX = "<XmlUtil>";
private static final StringERROR_PREFIX = "XmlUtil->";
private static Logger logger= Logger.getLogger(XmlUtil.class);
/**
*
* 2017年10月19日下午11:58:24
* @param <E>
* @param <K>
* @param xml
* @return
* @parameter
* Map<String,Object>
*
*/
public static Map<String, Object> xmlToMap(String xml) throws Exception{
logger.debug(DEBUG_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",xmlToMap begin");
logger.info(INFO_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",xmlToMap begin");
try {
Document doc = DocumentHelper.parseText(xml);
Map<String, Object> map = new HashMap<String, Object>();
if(doc == null)
return map;
Element root = doc.getRootElement();
System.out.println(root.getText());
for (@SuppressWarnings("unchecked")
Iterator iterator = root.elementIterator(); iterator.hasNext();) {
Element e = (Element) iterator.next();
@SuppressWarnings("unchecked")
List list = e.elements();
if(list.size() > 0){
map.put(e.getName(), Dom2Map(e));
}else
map.put(e.getName(), e.getText());
}
logger.debug(DEBUG_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",xmlToMap end");
logger.info(INFO_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",xmlToMap end");
return map;
} catch (DocumentException e) {
logger.error(ERROR_PREFIX+"execute xmlToMap occur error,the exception is:"+e);
throw e;
}
}
public static Map Dom2Map(Element e){
logger.debug(DEBUG_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",Dom2Map begin");
logger.info(INFO_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",Dom2Map begin");
Map map = new HashMap();
@SuppressWarnings("unchecked")
List list = e.elements();
if(list.size() > 0){
for (int i = 0;i < list.size(); i++) {
Element iter = (Element) list.get(i);
List mapList = new ArrayList();
if(iter.elements().size() > 0){
Map m = Dom2Map(iter);
if(map.get(iter.getName()) != null){
Object obj = map.get(iter.getName());
if(!obj.getClass().getName().equals("java.util.ArrayList")){
mapList = new ArrayList();
mapList.add(obj);
mapList.add(m);
}
if(obj.getClass().getName().equals("java.util.ArrayList")){
mapList = (List) obj;
mapList.add(m);
}
map.put(iter.getName(), mapList);
}else
map.put(iter.getName(), m);
}
else{
if(map.get(iter.getName()) != null){
Object obj = map.get(iter.getName());
if(!obj.getClass().getName().equals("java.util.ArrayList")){
mapList = new ArrayList();
mapList.add(obj);
mapList.add(iter.getText());
}
if(obj.getClass().getName().equals("java.util.ArrayList")){
mapList = (List) obj;
mapList.add(iter.getText());
}
map.put(iter.getName(), mapList);
}else
map.put(iter.getName(), iter.getText());
}
}
}else{
map.put(e.getName(), e.getText());
}
logger.debug(DEBUG_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",Dom2Map begin");
logger.info(INFO_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",Dom2Map begin");
return map;
}
/**
* 只返回根节点中的数据
* 解析对象:类似这种格式的xml文件<?xml version="1.0" encoding="utf-8"?><string xmlns="http://mms.10690007.com/">OK[3946470]</string>
*
* 2017年10月23日下午10:00:07
* @param xml
* @return
* @parameter
* String
*
*/
public static String xmlToString(String xml) throws Exception{
logger.debug(DEBUG_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",xmlToString begin");
logger.info(INFO_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",xmlToString begin");
try {
Document doc = DocumentHelper.parseText(xml);
if(doc == null)
return xml;
Element root = doc.getRootElement();
String rootContent = root.getText();
logger.debug(DEBUG_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",xmlToString end");
logger.info(INFO_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",xmlToString end");
return rootContent;
} catch (Exception e) {
logger.error(ERROR_PREFIX+"execute xmlToString occur error,the exception is:"+e);
throw e;
}
}
/**
* 测试代码
*/
public static void getWeather(){
try {
String queryUrl = "http://api.map.baidu.com/telematics/v3/weather?location=武汉&ak=8IoIaU655sQrs95uMWRWPDIa";
URL url = new URL(queryUrl);
URLConnection conn = url.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
String result = "";
while ((line=in.readLine())!=null){
result += line;
}
in.close();
System.out.println(result);
//解析返回的xml文件
Map<String,Object> map = xmlToMap(result);
for(String key:map.keySet()){
System.out.println("key="+key+",value="+map.get(key));
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static void main(String[] args) {
getWeather();
}
}