1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.dom4j.io.SAXWriter;
import java.io.ByteArrayInputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set;
public class XmlUtil {
public static String createXML(Map<String, String> map) { Document document = DocumentHelper.createDocument(); Element root = document.addElement("xml"); Set<String> keys = map.keySet(); for (String k : keys) { Element child = root.addElement(k); child.setText(map.get(k)); } return document.asXML(); }
public static Map<String, String> parseXml(String xml) { SAXReader reader = new SAXReader(); try { Document document = reader.read(new ByteArrayInputStream(xml.getBytes())); Element root = document.getRootElement(); List<Element> list = root.elements(); Map<String, String> map = new HashMap<>(); for (Element e : list) { map.put(e.getName(), e.getTextTrim()); } return map; } catch (DocumentException e) { e.printStackTrace(); } return null; } }
|