单节点xml转map 和 map转xml

直接看代码;

/**
 * @Author : lilong
 * @Description :xml  转 map
 * @Date : 15:37 2018/5/3
 * @Param : * xml格式字符串
 **/
public Map<String, String> xmlToMap(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());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return map;
}

/**
 * @Author : lilong
 * @Description :map 转 xml
 * @Date : 15:45 2018/5/4
 * @Param : 需要转的map
 **/
public 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/81663325