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("\n|\r", "");

try {

writer.close();

} catch (Exception ex) {

}

return output;

}

posted @ 2020-07-31 13:34  流浪者&乔木  阅读(428)  评论(0编辑  收藏  举报