• XML和Map之间互相转换


    /**

    * XML格式字符串转换为Map

    *

    * @param strXML XML字符串

    * @return XML数据转换后的Map

    * @throws Exception

    */

    public static Map<String, String> xmlToMap(String strXML) throws Exception {

    try {

    Map<String, String> data = new HashMap<String, String>();

    DocumentBuilder documentBuilder = newDocumentBuilder();

    InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));

    org.w3c.dom.Document doc = documentBuilder.parse(stream);

    doc.getDocumentElement().normalize();

    NodeList nodeList = doc.getDocumentElement().getChildNodes();

    for (int idx = 0; idx < nodeList.getLength(); ++idx) {

    Node node = nodeList.item(idx);

    if (node.getNodeType() == Node.ELEMENT_NODE) {

    org.w3c.dom.Element element = (org.w3c.dom.Element) node;

    data.put(element.getNodeName(), element.getTextContent());

    }

    }

    try {

    stream.close();

    } catch (Exception ex) {

    // do nothing

    }

    return data;

    } catch (Exception ex) {

    System.out.println("Invalid XML, can not convert to map. Error message: {}. XML content: {}"

    + ex.getMessage() + strXML);

    throw ex;

    }

     

    }

     

    /**

    * 将Map转换为XML格式的字符串

    *

    * @param data Map类型数据

    * @return XML格式的字符串

    * @throws Exception

    */

    public static String mapToXml(Map<String, String> data) throws Exception {

    org.w3c.dom.Document document = newDocument();

    org.w3c.dom.Element root = document.createElement("xml");

    document.appendChild(root);

    for (String key : data.keySet()) {

    String value = data.get(key);

    if (value == null) {

    value = "";

    }

    value = value.trim();

    org.w3c.dom.Element filed = document.createElement(key);

    filed.appendChild(document.createTextNode(value));

    root.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 writer = new StringWriter();

    StreamResult result = new StreamResult(writer);

    transformer.transform(source, result);

    String output = writer.getBuffer().toString(); // .replaceAll(" | ", "");

    try {

    writer.close();

    } catch (Exception ex) {

    }

    return output;

    }

  • 相关阅读:
    【GO】文件二进制读取
    【JAVA】IO FileInputStream 读取二进制文件
    【JAVA】Maven 常用命令
    【JAVA】java8 function apply() compose() andThen()
    【Java】Maven resoucese 目录文件获取
    【数据结构】线索二叉树
    【Java】Java中的null作为方法参数是被当做值传递
    【Python】《Effective Python》 读书笔记 (一)
    【Python】一个try/except/else/finally 组合使用的例子
    【数据结构】二叉树的创建与遍历
  • 原文地址:https://www.cnblogs.com/jiaoyixin/p/13409204.html
Copyright © 2020-2023  润新知