这两种方式只能从Map<String,String>格式转为xml格式
第一种:
public static String mapToXml(Map<String, String> data) throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = documentBuilder.newDocument();
org.w3c.dom.Element root = document.createElement("request"); //根节点
document.appendChild(root);
for (String key: data.keySet()) {
String value = data.get(key).toString();
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 e) {
e.getMessage();
}
return output;
}
第二种:
public static String mapToXml(Map<String, String> map) throws IOException {
Document d = DocumentHelper.createDocument();
Element root = d.addElement("request"); //根节点
Set<String> keys = map.keySet();
for(String key:keys) {
root.addElement(key).addText(String.valueOf(map.get(key)));
}
StringWriter sw = new StringWriter();
XMLWriter xw = new XMLWriter(sw);
xw.setEscapeText(false);
xw.write(d);
return sw.toString();
}
版权声明:本文为weixin_45151960原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。