注意:此工具类有局限性 /** * 2017年10月25日下午2:29:07 */ package com.jjmc.dcl.util; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.dom4j.DocumentHelper; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.Namespace; import org.jdom2.input.SAXBuilder; import org.xml.sax.InputSource; /** * * @author huangtao * 2017年10月25日下午2:29:07 * dclTask * @parameter * TODO * 使用jdom解析xml格式的string */ public class XmlUtilJdom { //日志 private static final StringDEBUG_PREFIX = "[XmlUtilJdom]"; private static final StringINFO_PREFIX = "<XmlUtilJdom>"; private static final StringERROR_PREFIX = "XmlUtilJdom->"; private static Logger logger= Logger.getLogger(XmlUtilJdom.class); /** * * 用Jdom解析xml格式的字符串,返回List<Map<String,Object>> * * 2017年10月26日上午12:15:33 * @param xmlDoc * @return * @throws Exception * @parameter * List<Map<String,Object>> * */ public static List<Map<String,Object>> xmlToList(String xmlDoc) throws Exception{ logger.debug(DEBUG_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",xmlToList begin"); logger.info(INFO_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",xmlToList begin"); try { List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); //创建一个新的字符串 StringReader read = new StringReader(xmlDoc); //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入 InputSource source = new InputSource(read); //创建一个新的SAXBuilder SAXBuilder sb = new SAXBuilder(); //通过输入源构造一个Document Document doc = sb.build(source); //取的根元素 Element root = doc.getRootElement(); // System.out.println(root.getName());//输出根元素的名称(测试) //得到根元素所有子元素的集合 List jiedian = root.getChildren(); //获得XML中的命名空间(XML中未定义可不写) Namespace ns = root.getNamespace(); //获取根元素里的nextID // String nextID = root.getAttributeValue("nextID"); Element et = null; for(int i=0;i<jiedian.size();i++){ et = (Element) jiedian.get(i);//循环依次得到子元素 Map<String,Object> map = new HashMap<String,Object>(); map.put("id", et.getChild("id",ns).getText()); map.put("mobile", et.getChild("mobile",ns).getText()); map.put("SrcNumber", et.getChild("SrcNumber",ns).getText()); map.put("TokenID", et.getChild("TokenID",ns).getText()); map.put("MessageID", et.getChild("MessageID",ns).getText()); map.put("DeliverState", et.getChild("DeliverState",ns).getText()); map.put("org_messageid", et.getChild("org_messageid",ns).getText()); map.put("insertTime", et.getChild("insertTime",ns).getText()); list.add(map); } logger.debug(DEBUG_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",xmlToList end"); logger.info(INFO_PREFIX+"current time is:"+DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")+",xmlToList end"); return list; } catch (JDOMException e1) { logger.error(ERROR_PREFIX+"execute xmlToList occur error,the exception is:"+e1); throw e1; } catch (IOException e2) { logger.error(ERROR_PREFIX+"execute xmlToList occur error,the exception is:"+e2); throw e2; } } /** * 只返回根节点中的数据 * 解析对象:类似这种格式的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 { List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); //创建一个新的字符串 StringReader read = new StringReader(xml); //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入 InputSource source = new InputSource(read); //创建一个新的SAXBuilder SAXBuilder sb = new SAXBuilder(); //通过输入源构造一个Document Document doc = sb.build(source); //取的根元素 Element root = doc.getRootElement(); // System.out.println(root.getName());//输出根元素的名称(测试) //得到根元素所有子元素的集合 List jiedian = root.getChildren(); //获得XML中的命名空间(XML中未定义可不写) Namespace ns = root.getNamespace(); //获取根元素里的nextID String nextID = root.getAttributeValue("nextID"); 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 nextID; } catch (Exception e) { logger.error(ERROR_PREFIX+"execute xmlToString occur error,the exception is:"+e); throw e; } } public static void main(String[] args){ XmlUtilJdom doc = new XmlUtilJdom(); // String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+ // "<Result xmlns=\"http://www.fiorano.com/fesb/activity/DBQueryOnInput2/Out\">"+ // "<result>"+ // "<id>0</id>"+ // "<Mobile>123456789</Mobile>"+ // "<Token_Id>123456789</Token_Id>"+ // "<MessageId>00000001</MessageId>"+ // "<Deliverstate>1 </Deliverstate>"+ // "<insertTime>2017-04-01 12:23:13 0</insertTime>"+ // "</result>"+ // "<result>"+ // "<id>1</id>"+ // "<Mobile>123456789</Mobile>"+ // "<Token_Id>123456789</Token_Id>"+ // "<MessageId>00000002</MessageId>"+ // "<Deliverstate>1</Deliverstate>"+ // "<insertTime>2017-07-01 12:23:13 0</insertTime>"+ // "</result>"+ // "</Result>"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><NewDataSet nextID=\"0000001\"><result><id>2117752</id><mobile>1234567890</mobile><SrcNumber>123456789</SrcNumber><TokenID>1234567890</TokenID><MessageID>000001</MessageID><DeliverState>1</DeliverState><org_messageid>000001</org_messageid><insertTime>2017-10-19 16:40:23 0</insertTime></result></NewDataSet>"; List<Map<String, Object>> list; try { list = doc.xmlToList(xml); for(Map<String,Object> l:list){ System.out.println("===================="); for(String key:l.keySet()){ System.out.println("key="+key+",value="+l.get(key)); } System.out.println("===================="); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }