字符串xml格式轉List集合的那些坑

/**
	 * xml字符串轉list集合
	 * @param xml
	 * @return
	 */
	public static List<Map<String,Object>> xmlToList(String xml){
		if(null == xml || "".equals(xml)){
			Logger.getLogger(XmlUtil.class).info("xml爲空");
			return null;
		}
		List<Map<String, Object>> list = new ArrayList();
		xml =xml.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "").replace("\n","").replace(" ","");;
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			Logger.getLogger(XmlUtil.class).info(xml);
			document = reader.read(new ByteArrayInputStream(xml.getBytes("utf-8")));
			Element root = document.getRootElement();//獲取根元素
	        List<Element> childElements = root.elements();//獲取當前元素下的全部子元素
	        
	        
	        for (Element child : childElements) {//循環輸出全部信息
	        	Map<String, Object> map = new HashMap();//每個實體
	        	List<Element> infos = child.elements();//每個對象信息
	            for (Element info : infos) {
	                String name = info.getName();//獲取當前元素名
	                String text = info.getText();//獲取當前元素值
	                map.put(name,text);
	            }
	            list.add(map);
	            map=null;//回收map
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

這裏面有兩個關鍵點:

  1. 字符串空格和行,必須用空字符串替換她們,如下:
xml =xml.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "").replace("\n","").replace(" ","");

 

  1. 字符串字節碼,必須轉爲utf-8,如下:
document = reader.read(new ByteArrayInputStream(xml.getBytes("utf-8")));

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章