package util;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 字符串和xml互转工具类
* @author:
* @date
* @version v1.0.0
*/
public
class XmlUtil {
private static Logger log = LoggerFactory.getLogger(XmlUtil.class);
private static SAXReader saxReader = new SAXReader();
private Document document;
public XmlUtil(){
}
public XmlUtil(String xmlString) throws UnsupportedEncodingException, DocumentException{
this.document = saxReader.read(new ByteArrayInputStream(formatting(xmlString).getBytes("UTF-8")));
}
private static String formatting(String xmlString){
return xmlString.replaceAll("<", "<").replaceAll(">", ">");
}
/**
* 从xml中根据节点名查找节点值
* @author:
* @date
* @param responseXml
* @param nodeName
* @return nodeValue
* @version v1.0.0
*/
public Map<String,String> getGroupNode(String[] nodes){
Map<String,String> map = new HashMap<String,String>();
String nodeValue = null;
try {
for(int i=0;i<nodes.length;i++){
List<Node> temp = document.selectNodes("//"+nodes[i]+"[1]");
if(temp != null && temp.size()>0) {
for(int m=0;m<temp.size();m++){
nodeValue = temp.get(m).getText();
map.put(nodes[i], nodeValue);
}
}
}
} catch (Exception e) {
log.error("
解析xml
异常:{}",e);
}
return map;
}
/**
* 返回请求应答消息给请求方,0:成功;1:失败 ; 2: 受理中
* @param resultCode 返回码
* @param resultDesc 返回结果描述
*/
public static String makeAnswerXml(String resultCode,String resultDesc){
return "<resultCode>"+resultCode+"</resultCode><resultDesc>"+resultDesc+"</resultDesc>";
}
}