不多说直接上代码,代码如下:
/**
* @Title: getMapFromXML
* @Description: xml转map
* @param xmlStr
* @return Map<String, Object>
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
**/
public static Map<String, Object> getMapFromXML(String xmlStr)
throws ParserConfigurationException, IOException, SAXException
{
SortedMap<String, Object> map = new TreeMap<String, Object>();
Document document = null;
try
{
document = DocumentHelper.parseText(xmlStr);
}
catch(DocumentException e)
{
e.printStackTrace();
}
Element root = document.getRootElement();
List<Element> list = root.elements();
for (Element element : list)
{
String key = element.getName();
String value = element.getText();
map.put(key, value);
}
return map;
}
上面引入的类如下:
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.xml.parsers.ParserConfigurationException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.xml.sax.SAXException;
至此结束,希望对小伙伴们有帮助!