将对象转换成xml,需要先导入XStream jar包,下载地址:http://x-stream.github.io/download.html
XStream xs = new XStream(); String xmlStr= xs.toXML(obj);
将对象转换成xml,并用流输出
XStream xs = new XStream(); xs.toXML(obj,outputStream);
将xml输入流转换成map,需要先导入dom4j jar包,下载地址:https://sourceforge.net/projects/dom4j/files
Map<String, String> map = new HashMap<String, String>();
SAXReader sr = new SAXReader();
Document doc = null; try { doc = sr.read(inputStream); } catch (DocumentException e) { e.printStackTrace(); } Element root = doc.getRootElement(); List<Element> elements = root.elements(); for (Element element : elements) { map.put(element.getName(), element.getText()); }
xml输入流转String
SAXReader sr = new SAXReader(); Document doc = null; try { doc = sr.read(is); } catch (DocumentException e) { e.printStackTrace(); } return doc.getRootElement().asXML();
String形式xml转map
Document doc = null; try { doc = DocumentHelper.parseText(xml); } catch (DocumentException e) { e.printStackTrace(); } Element root = doc.getRootElement(); List<Element> elements = root.elements(); Map<String, String> map = new HashMap<String, String>(); for (Element element : elements) { map.put(element.getName(), element.getText()); } return map;