package com.nuzar.fcms.common.core.business.utils;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.nuzar.cloud.common.utils.StringUtils;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.w3c.dom.Node;
import javax.validation.constraints.NotNull;
import java.io.StringReader;
import java.util.*;
/**
* @description:
* @auther: zsy
* @date: 2022/9/23 17:55
*/
public class XmlUtils {
/**
* xml格式转换
* @param xml
* @param map
*/
public static void parseXmlToMap(String xml, @NotNull Map<String, String> map) {
try {
SAXReader reader = new SAXReader();
org.dom4j.Document doc = reader.read(new StringReader(xml));
Element root = doc.getRootElement();
String path = "";
if (map.containsKey(root.getName().trim())) {
path = map.get(root.getName().trim());
map.remove(root.getName().trim());
}
for (Iterator i = root.elementIterator(); i.hasNext(); ) {
Element element = (Element) i.next();
if (element.isTextOnly()) {
if (path.length() > 0) {
map.put(path + element.getName().trim(), element.getTextTrim());
} else {
map.put(element.getName().trim(), element.getTextTrim());
}
} else {
map.put(element.getName().trim(), path + element.getName().trim() + ".");
parseXmlToMap(element.asXML(), map);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根据节点获取值
* @param xml
* @param element
* @return
*/
public static <T> T getValueByElement(String xml, String element, Class<T> clazz){
Map<String, String> resultMap = Maps.newHashMap();
parseXmlToMap(xml, resultMap);
return JSONUtil.toBean(resultMap.get(element), clazz);
}
/**
*
* @param xPath
* @param xmlMap
* @return
*/
public static Object getValueByXPath(Queue<String> xPath, Map<String, Object> xmlMap) {
if (xPath.size() == 1) {
return xmlMap == null ? null : xmlMap.get(xPath.poll());
}
return getValueByXPath(xPath, (Map<String, Object>) xmlMap.get(xPath.poll()));
}
public static Object getValueByXPath(Queue<String> xPath, String xmlStr) {
return getValueByXPath(xPath, XmlUtil.xmlToMap(xmlStr));
}
public static Object getValueByXPath(String xPath, String xmlStr) {
return getValueByXPath(buildPath(xPath), XmlUtil.xmlToMap(xmlStr));
}
public static Object getValueByXPath(Queue<String> xPath, Node node) {
return getValueByXPath(xPath, XmlUtil.xmlToMap(node));
}
public static Object getValueByXPath(String xPath, Node node) {
return getValueByXPath(buildPath(xPath), XmlUtil.xmlToMap(node));
}
public static Queue<String> buildPath(String xPath) {
if (xPath.startsWith("/")) {
xPath.substring(1);
}
String[] split = xPath.split("/");
Queue<String> queue = new LinkedList<>();
for (String s :
split) {
if (StringUtils.isNotEmpty(s)) {
queue.add(s);
}
}
return queue;
}
}