xml 转 map &&map 转 xml

   /**
     * @Author : lilong
     * @Description :xml  转 map
     * @Date : 15:37 2018/5/3
     * @Param : * xml格式字符串
     **/
    private static Map<String, String> xml2Map(String xml) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            Document doc = DocumentHelper.parseText(xml);//将xml转为dom对象
            Element root = doc.getRootElement();//获取根节点
            List<Element> elements = root.elements();//获取这个节点里面的所有的元素,也可以element.elements("userList")指定获取子元素
            for (Object obj : elements) {  //遍历元素
                root = (Element) obj;
                map.put(root.getName(), root.getTextTrim());
                System.out.println(root.getName() + "--" + root.getTextTrim());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
/**
* @Author : lilong
* @Description :map 转 xml
* @Date : 15:45 2018/5/4
* @Param : map 格式参数
**/
    private static String mapToXml(Map<String, String> map) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        org.w3c.dom.Document document = documentBuilder.newDocument();
        org.w3c.dom.Element element = document.createElement("xml");
        document.appendChild(element);
        for (String key : map.keySet()) {
            String value = map.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            element.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter write = new StringWriter();
        StreamResult result = new StreamResult(write);
        transformer.transform(source, result);
        String output = write.getBuffer().toString();////.replaceAll("\n|\r", "");
        try {
            write.close();
        } catch (Exception e) {

        }
        return output;
    }

猜你喜欢

转载自blog.csdn.net/qq_19167629/article/details/80196216
今日推荐