码上敲享录 > java入门知识分享 > java将Map转换为XML格式的字符串

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

上一章章节目录下一章 2018-08-09已有3504人阅读 评论(0)

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

解决方法:

源码如下,复制即可使用

public static String mapToXml(Map<String, String> data) throws Exception {
   DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.
newInstance();
documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
documentBuilderFactory.setXIncludeAware(false);
documentBuilderFactory.setExpandEntityReferences(false);
DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = documentBuilder.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("\n|\r", "");
try {
       writer.close()
;
}
catch (Exception ex) {
   }
return output;
}

本文地址:http://www.yayihouse.com/yayishuwu/chapter/1454

向大家推荐《Activiti工作流实战教程》:https://xiaozhuanlan.com/activiti
0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交