xml格式字符串轉為Map


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

 

/**
* XML格式字符串轉換為Map
* @作者 廖正瀚
* @日期 2017年12月1日
* @param xml
* @param charset
* @return
* @throws DocumentException
* @throws UnsupportedEncodingException
*/
public static Map<String, String> xmlToMap(String xml, String charset) throws UnsupportedEncodingException, DocumentException{

Map<String, String> respMap = new HashMap<String, String>();

SAXReader reader = new SAXReader();
Document doc = reader.read(new ByteArrayInputStream(xml.getBytes(charset)));
Element root = doc.getRootElement();
xmlToMap(root, respMap);
return respMap;
}

public static Map<String, String> xmlToMap(Element tmpElement, Map<String, String> respMap){

if (tmpElement.isTextOnly()) {
respMap.put(tmpElement.getName(), tmpElement.getText());
return respMap;
}

@SuppressWarnings("unchecked")
Iterator<Element> eItor = tmpElement.elementIterator();
while (eItor.hasNext()) {
Element element = eItor.next();
xmlToMap(element, respMap);
}
return respMap;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM