<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.1</version>
</dependency>
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@SuppressWarnings("unused")
public final class XmlUtils {
public static Map<String, String> xmlToMap(String xml) {
try {
Map<String, String> data = new HashMap<>(16);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.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());
}
}
stream.close();
return data;
} catch (Exception e) {
log.error("XML格式字符串转换为Map (单层) 出现异常", e);
return null;
}
}
public static String mapToXml(Map<String, String> data) {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
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();
writer.close();
return output;
} catch (Exception e) {
log.error(" 将Map转换为XML格式的字符串 (单层) 出现异常", e);
return null;
}
}
public static Map<String, Object> multilayerXmlToMap(String xml) {
Document doc = null;
try {
doc = DocumentHelper.parseText(xml);
} catch (DocumentException e) {
log.error("xml字符串解析,失败 ", e);
}
Map<String, Object> map = new HashMap<>(16);
if (null == doc) {
return map;
}
Element rootElement = doc.getRootElement();
recursionXmlToMap(rootElement, map);
return map;
}
private static void recursionXmlToMap(Element element, Map<String, Object> outmap) {
List<Element> list = element.elements();
int size = list.size();
if (size == 0) {
outmap.put(element.getName(), element.getTextTrim());
} else {
Map<String, Object> innermap = new HashMap<>(16);
list.forEach(childElement -> recursionXmlToMap(childElement, innermap));
outmap.put(element.getName(), innermap);
}
}
public static String multilayerMapToXml(Map<String, Object> map, boolean isCdata) {
String parentName = "xml";
Document doc = DocumentHelper.createDocument();
doc.addElement(parentName);
String xml = recursionMapToXml(doc.getRootElement(), parentName, map, isCdata);
return formatXml(xml);
}
@SuppressWarnings("unchecked")
private static String recursionMapToXml(Element element, String parentName, Map<String, Object> map, boolean isCdata) {
Element xmlElement = element.addElement(parentName);
map.keySet().forEach(key -> {
Object obj = map.get(key);
if (obj instanceof Map) {
recursionMapToXml(xmlElement, key, (Map<String, Object>) obj, isCdata);
} else {
String value = obj == null ? "" : obj.toString();
if (isCdata) {
xmlElement.addElement(key).addCDATA(value);
} else {
xmlElement.addElement(key).addText(value);
}
}
});
return xmlElement.asXML();
}
public static String formatXml(String xml) {
String requestXml = null;
try {
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(xml));
if (null != document) {
StringWriter stringWriter = new StringWriter();
OutputFormat format = new OutputFormat(" ", true);
format.setNewLineAfterDeclaration(false);
format.setSuppressDeclaration(false);
format.setNewlines(true);
XMLWriter writer = new XMLWriter(stringWriter, format);
writer.write(document);
writer.flush();
writer.close();
requestXml = stringWriter.getBuffer().toString();
}
return requestXml;
} catch (Exception e) {
log.error("格式化xml,失败 ", e);
return null;
}
}
}