欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

工具类-Map处理类

程序员文章站 2022-07-15 14:57:05
...

Xml处理类

工具一

package com.xxx.xxx.xxxx;

import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

public class AnalyticXmlUtil {

	private transient static Log logger = LogFactory.getLog(AnalyticXmlUtil.class);
    
 

	public static Map<String, String> AnalyticXml(String xmlDoc) {
		Map<String, String> map = new HashMap<String, String>();
		StringReader read = null;
		try {
			 创建一个新的字符串
			read = new StringReader(xmlDoc);
			 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			InputSource source = new InputSource(read);
			 创建一个新的SAXBuilder
			SAXBuilder sb = new SAXBuilder();
			 通过输入源构造一个Document
			Document doc = sb.build(read.toString());
			 取的根元素
			Element root = doc.getRootElement();
			 得到根元素所有子元素的集合
			List jiedian = root.getChildren();
			 获得XML中的命名空间(XML中未定义可不写)
			Namespace ns = root.getNamespace();
			Element et = null;
			for (int i = 0; i < jiedian.size(); i++) {
				et = (Element) jiedian.get(i); 循环依次得到子元素
				map.put(et.getName(), et.getText());
			}
		} catch (Exception e) {
			logger.error("AnalyticXml 解析失败:" + e.getMessage());
		}finally{
			if(read != null){
				read.close();
			}
		}
		return map;
	}

	public static Map<String, String> AnalyticIcbcFnishXml(String xmlDoc) {
		Map<String, String> map = new HashMap<String, String>();
		StringReader read = null;
		try {
			 创建一个新的字符串
			read = new StringReader(xmlDoc);
			 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			InputSource source = new InputSource(read);
			 创建一个新的SAXBuilder
			SAXBuilder sb = new SAXBuilder();
			 通过输入源构造一个Document
			Document doc = sb.build(read.toString());
			 取的根元素
			Element root = doc.getRootElement();
			 取应答信息
			List<Element> list = root.getChildren();
			for (int i = 0; i < list.size(); i++) {
				List<Element> childList = list.get(i).getChildren();
				for (int j = 0; j < childList.size(); j++) {
					Element e = childList.get(j);
					map.put(e.getName(), e.getText());
				}
			}
		} catch (Exception e) {
			logger.error("AnalyticIcbcFnishXml 解析失败:" + e.getMessage());
			Map<String, String> errorMap = new HashMap<String, String>();
			errorMap.put("40972", "API查询的订单不存在");
			errorMap.put("40973", "API查询过程中系统异常");
			errorMap.put("40976", "API查询系统异常");
			errorMap.put("40977", "商户证书信息错");
			errorMap.put("40978", "解包商户请求数据报错");
			errorMap.put("40980", "API查询过程中系统异常");
			errorMap.put("40981", "给商户打包返回数据错");
			errorMap.put("40982", "系统错误");
			errorMap.put("40983", "查询的订单不唯一");
			errorMap.put("40987", "请求数据中接口名错误");
			errorMap.put("40947", "商户代码或者商城账号有误");
			errorMap.put("40948", "商城状态非法");
			errorMap.put("40949", "商城类别非法");
			errorMap.put("40950", "商城应用类别非法");
			errorMap.put("40951", "商户证书id状态非法");
			errorMap.put("40952", "商户证书id未绑定");
			errorMap.put("40953", "商户id权限非法");
			errorMap.put("40954", "检查商户状态时数据库异常");
			map.put("bankRem", errorMap.get(xmlDoc));
		}finally{
			if(read != null){
				read.close();
			}
		}
		return map;
	}

	public static Map<String, String> AnalyticIcbcPriXml(String xmlDoc, int type) {
		Map<String, String> map = new HashMap<String, String>();
		try {
			String[] str = xmlDoc.split("</pubpackage>");
			if (str.length == 1) {
				String pub = str[0] = "<?xml version='1.0' encoding='UTF-8'?>" + str[0].trim() + "</pubpackage>";
				map = AnalyticIcbcPriPubXml(pub);
			} else {
				String pub = "<?xml version='1.0' encoding='UTF-8'?>" + str[0].trim() + "</pubpackage>";
				map = AnalyticIcbcPriPubXml(pub);
				String busi = "<?xml version='1.0' encoding='UTF-8'?>" + str[1].trim();
				Map<String, String> busiMap = null;
				if (type == 1) {
					busiMap = AnalyticIcbcPriBusi2Xml(busi);
				} else {
					busiMap = AnalyticIcbcPriBusiXml(busi);
				}
				map.putAll(busiMap);
			}
		} catch (Exception e) {
			logger.error("AnalyticIcbcFnishXml 解析失败:" + e.getMessage());
		}
		return map;
	}

	public static String getBody(String xmlStr) {
		String method = "getBody";
		try {
			int first = xmlStr.indexOf("<pub>");
			int end = xmlStr.indexOf("<signature>");
			return xmlStr.substring(first, end);
		} catch (Exception e) {
			logger.error(method + "获取工行对私报文的中间部分出错:" + e.getMessage());
			return null;
		}
	}
	

	public static Map<String, String> AnalyticIcbcPriPubXml(String xmlDoc) {
		Map<String, String> map = new HashMap<String, String>();
		StringReader read = null;
		try {
			 创建一个新的字符串
			read = new StringReader(xmlDoc);
			 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			 InputSource source = new InputSource(read);
			 创建一个新的SAXBuilder
			SAXBuilder sb = new SAXBuilder();
			 通过输入源构造一个Document
			Document doc = sb.build(read);
			 取的根元素
			Element root = doc.getRootElement();
			 取应答信息
			List<Element> list = root.getChildren();
			for (int i = 0; i < list.size(); i++) {
				List<Element> childList = list.get(i).getChildren();
				for (int j = 0; j < childList.size(); j++) {
					Element e = childList.get(j);
					map.put(e.getName(), e.getText());
				}
			}
		} catch (Exception e) {
			logger.error("AnalyticIcbcPriPubXml 解析失败:" + e.getMessage());
		}finally{
			if(read != null){
				read.close();
			}
		}
		return map;
	}

	public static Map<String, String> AnalyticIcbcPriBusiXml(String xmlDoc) {
		Map<String, String> map = new HashMap<String, String>();
		StringReader read = null;
		try {
			 创建一个新的字符串
			read = new StringReader(xmlDoc);
			 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			InputSource source = new InputSource(read);
			 创建一个新的SAXBuilder
			SAXBuilder sb = new SAXBuilder();
			 通过输入源构造一个Document
			Document doc = sb.build(read);
			 取的根元素
			Element root = doc.getRootElement();
			 取应答信息
			List<Element> list = root.getChildren();
			for (int i = 0; i < list.size(); i++) {
				List<Element> childList = list.get(i).getChildren();
				for (int j = 0; j < childList.size(); j++) {
					List<Element> child2List = childList.get(j).getChildren();
					for (int k = 0; k < child2List.size(); k++) {
						Element e = child2List.get(k);
						map.put(e.getName(), e.getText());
					}
				}
			}
		} catch (Exception e) {
			logger.error("AnalyticIcbcPriBusiXml 解析失败:" + e.getMessage());
		}finally{
			if(read != null){
				read.close();
			}
		}
		return map;
	}

	public static Map<String, String> AnalyticIcbcPriBusi2Xml(String xmlDoc) {
		Map<String, String> map = new HashMap<String, String>();
		StringReader read = null;
		try {
			 创建一个新的字符串
			read = new StringReader(xmlDoc);
			 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			InputSource source = new InputSource(read);
			 创建一个新的SAXBuilder
			SAXBuilder sb = new SAXBuilder();
			 通过输入源构造一个Document
			Document doc = sb.build(read);
			 取的根元素
			Element root = doc.getRootElement();
			 取应答信息
			List<Element> list = root.getChildren();
			for (int i = 0; i < list.size(); i++) {
				List<Element> childList = list.get(i).getChildren();
				for (int j = 0; j < childList.size(); j++) {
					List<Element> child2List = childList.get(j).getChildren();
					for (int k = 0; k < child2List.size(); k++) {
						List<Element> child3List = child2List.get(k).getChildren();
						for (int h = 0; h < child3List.size(); h++) {
							Element e = child3List.get(h);
							map.put(e.getName(), e.getText());
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("AnalyticIcbcPriBusiXml 解析失败:" + e.getMessage());
		}finally{
			if(read != null){
				read.close();
			}
		}
		return map;
	}
}

工具二

package com.xxx.xxx.util.payutil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class XmlUtils {

   public static final String UTF8_ENCODING = "UTF-8";

   /**
    * 以字符串查找的试获取xml文本中节点的值
    *
    * @param nodeStart
    *            节点开始标签 eg :&lt;TransactionID&gt;
    * @param nodeEnd
    *            节点结束标签 eg :&lt;/TransactionID&gt;
    * @param src
    *            原字符串
    * @return
    */
   public static String parseNodeValueFromXml(String nodeStart, String nodeEnd, String src) {
      int nodeStartLength = nodeStart.length();
      int start = src.indexOf(nodeStart);
      int end = src.indexOf(nodeEnd);
      if (start > -1 && end > -1) {
         return src.substring(start + nodeStartLength, end);
      }
      return "";
   }

   /**
    * <p>
    * 获取xml字符串中指定节点的值,对应节点中可能包含&lt;![CDATA[xxxx]]&gt;的(如:&lt;attach&gt;&lt; ![
    * CDATA[支付测试]] &gt;&lt;/attach&gt;)使用此函数<br>
    * 确定节点不包含&lt;![CDATA[xxxx]]&gt;建议使用 函数parseNodeValueFromXml
    * </p>
    *
    * @param nodeStart
    *            节点开始标签 eg : &lt;TransactionID&gt;
    * @param nodeEnd
    *            节点结束标签 eg : &lt;/TransactionID&gt;
    * @param src
    *            原字符串
    * @return
    */
   public static String getNodeValueFromXml(String nodeStart, String nodeEnd, String src) {
      String rtnStr = "";
      int nodeStartLength = nodeStart.length();
      int start = src.indexOf(nodeStart);
      int end = src.indexOf(nodeEnd);
      if (start > -1 && end > -1) {
         // 先从xml字符串中截取出对应节点的内容
         rtnStr = src.substring(start + nodeStartLength, end);
      }
      rtnStr = rtnStr.substring(9, rtnStr.lastIndexOf("]]>"));
      return rtnStr;
   }

   /**
    * 获取xml字符串中指定节点的值,对应节点中可能包含"&lt;![CDATA[xxxx]]>"的(如:
    * <attach>&lt;![CDATA[支付测试]]></attach>)使用此函数<br>
    * 确定节点不包含"&lt;![CDATA[xxxx]]>"建议使用 函数parseNodeValueFromXml
    *
    * @param nodeName
    *            节点名字eg: xml
    * @param xmlStr
    *            原字符串
    * @return
    */
   public static String getNodeValueFromXml(String nodeName, String xmlStr) {
      String nodeStart = "<" + nodeName + ">";
      String nodeEnd = "</" + nodeName + ">";
      return getNodeValueFromXml(nodeStart, nodeEnd, xmlStr);
   }

   /**
    * 替换xml中节点的值,只适合替换报文中只有一个指定名字的节点
    *
    * @param nodeStart
    *            节点开始标签 eg :&lt;TransactionID>
    * @param nodeEnd
    *            节点结束标签 eg :&lt;/TransactionID>
    * @param relacement
    *            节点替换的内容
    * @param xml
    *            原字符串
    * @return
    */
   public static String relaceNodeContent(String nodeStart, String nodeEnd, String relacement, String xml) {
      int nodeStartLength = nodeStart.length();
      int start = xml.indexOf(nodeStart);
      int end = xml.indexOf(nodeEnd);

      if (start > -1 && end > -1) {
         String segStart = xml.substring(0, start + nodeStartLength);
         String segEnd = xml.substring(end, xml.length());
         return segStart + relacement + segEnd;
      }
      return xml;
   }

   /**
    * 去除xmlStr报文中A节点下的数据用B节点替换,主要用于去除“&lt;![CDATA[&lt;?xml version="1.0"
    * encoding="UTF-8"?>”和 “]]>”
    *
    * @param xmlStr
    *            原xml字符串
    * @param fromSta
    *            开始节点
    * @param fromEnd
    *            结束节点
    * @param toSta
    *            开始节点
    * @param toEnd
    *            结束节点
    * @return
    */
   public static String parseElement(String xmlStr, String fromSta, String fromEnd, String toSta, String toEnd) {
      // 替换的数据
      String rspStr = parseNodeValueFromXml(fromSta, fromEnd, xmlStr);
      rspStr = fromSta + rspStr + fromEnd;
      // 将xmlStr数据下to节点中的数据用中rspStr数据替换
      String newXmlStr = relaceNodeContent(toSta, toEnd, rspStr, xmlStr);
      return newXmlStr;
   }

   /**
    * 去除报文中的空格、回车、换行符、制表符
    *
    * @param str
    * @return
    */
   public static String replaceBlank(String str) {
      String dest = "";
      if (str != null) {
         Pattern p = Pattern.compile("\\s*|\t|\r|\n");
         Matcher m = p.matcher(str);
         dest = m.replaceAll("");
         dest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + dest.substring(36);
      }
      return dest;
   }

}

工具三

package com.xxxx.aipay.util.payutil;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class XmlStringUtil {


	/**
	 * url请求的参数转MAP
	 *
	 * @param queryString
	 *            请求的参数串
	 * @param enc
	 *            编码
	 * @return
	 */
	public static Map<String, String> getRequestParam(String queryString) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		if (queryString != null && queryString.length() > 0) {
			int ampersandIndex, lastAmpersandIndex = 0;
			String subStr, param, value;
			do {
				ampersandIndex = queryString.indexOf('&', lastAmpersandIndex) + 1;
				if (ampersandIndex > 0) {
					subStr = queryString.substring(lastAmpersandIndex,
							ampersandIndex - 1);
					lastAmpersandIndex = ampersandIndex;
				} else {
					subStr = queryString.substring(lastAmpersandIndex);
				}

				int index = subStr.indexOf("=");
				param = subStr.substring(0, index);
				value = subStr.length() == index + 1 ? "" : subStr
						.substring(index + 1);
				if(!"sign".equals(param)&&!"signature".equals(param)){
					value=URLDecoder.decode(value);
				}
				paramsMap.put(param, value);
			} while (ampersandIndex > 0);
		}
		return paramsMap;
	}


	/**
	 * url请求的参数转MAP
	 *
	 * @param queryString
	 *            请求的参数串
	 * @param enc
	 *            编码
	 * @return
	 */
	public static Map<String, String> getParamsMap(String queryString,
												   String enc) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		if (queryString != null && queryString.length() > 0) {
			int ampersandIndex, lastAmpersandIndex = 0;
			String subStr, param, value;
			do {
				ampersandIndex = queryString.indexOf('&', lastAmpersandIndex) + 1;
				if (ampersandIndex > 0) {
					subStr = queryString.substring(lastAmpersandIndex,
							ampersandIndex - 1);
					lastAmpersandIndex = ampersandIndex;
				} else {
					subStr = queryString.substring(lastAmpersandIndex);
				}

				int index = subStr.indexOf("=");
				param = subStr.substring(0, index);
				value = subStr.length() == index + 1 ? "" : subStr
						.substring(index + 1);
				try {
//					if(!"SignValue".equals(param)){
//					value = URLDecoder.decode(value, enc);
//					}
					paramsMap.put(param, value);
				} catch (Exception ignored) {
					return null;
				}
			} while (ampersandIndex > 0);
		} else {
			return null;
		}

		return paramsMap;
	}

	/**
	 * 替换xml中在某个字符串之后节点的值,只适合替换报文中只有一个指定名字的节点
	 *
	 * @param nodeStart
	 *            节点开始标签 eg :<TransactionID>
	 * @param nodeEnd
	 *            节点结束标签 eg :</TransactionID>
	 * @param relacement
	 *            节点替换的内容
	 * @param src
	 *            原字符串
	 * @return
	 */
	public static String relaceNodeContentAfter(String nodeStart, String nodeEnd,String afterStart,
												String relacement, String src) {
		int nodeStartLength = nodeStart.length();
		int startAfter = src.indexOf(afterStart);
		int start = src.indexOf(nodeStart,startAfter);
		int end = src.indexOf(nodeEnd,startAfter);

		if(start>-1 && end>-1){
			String segStart = src.substring(0, start + nodeStartLength);
			String segEnd = src.substring(end, src.length());
			return segStart + relacement + segEnd;
		}
		return src;
	}
	/**
	 * 替换xml中节点的值,只适合替换报文中只有一个指定名字的节点
	 *
	 * @param nodeStart
	 *            节点开始标签 eg :<TransactionID>
	 * @param nodeEnd
	 *            节点结束标签 eg :</TransactionID>
	 * @param relacement
	 *            节点替换的内容
	 * @param src
	 *            原字符串
	 * @return
	 */
	public static String relaceNodeContent(String nodeStart, String nodeEnd,
										   String relacement, String src) {
		int nodeStartLength = nodeStart.length();
		int start = src.indexOf(nodeStart);
		int end = src.indexOf(nodeEnd, start);

		if(start>-1 && end>-1){
			String segStart = src.substring(0, start + nodeStartLength);
			String segEnd = src.substring(end, src.length());
			return segStart + relacement + segEnd;
		}
		return src;
	}
	/**
	 * 获取xml文本中节点的值
	 *
	 * @param nodeStart
	 *            节点开始标签 eg :<TransactionID>
	 * @param nodeEnd
	 *            节点结束标签 eg :</TransactionID>
	 * @param src
	 *            原字符串
	 * @return
	 */
	public static String parseNodeValueFromXml(String nodeStart,
											   String nodeEnd, String src) {
		int nodeStartLength = nodeStart.length();
		int start = src.indexOf(nodeStart);
		int end = src.indexOf(nodeEnd);
		if(start>-1&&end>-1){
			String nodeVal = src.substring(start + nodeStartLength, end);
			return nodeVal;
		}
		return "";
	}

	/**
	 * 获取xml中xpath节点的值
	 *
	 * @param xml
	 * @param encoding
	 * @param xpath
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws DocumentException
	 */
	public static String getNodeValFromXml(String xml, String encoding,
										   String xpath) throws UnsupportedEncodingException,
			DocumentException {
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(new ByteArrayInputStream(xml
				.getBytes(encoding)));
		return document.selectSingleNode(xpath).getText();
	}

	/**
	 * 获取xml中xpath节点的值
	 *
	 * @param in
	 * @param xpath
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws DocumentException
	 */
	public static String getNodeValFromStream(InputStream in, String xpath)
			throws UnsupportedEncodingException, DocumentException {
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(in);
		return document.selectSingleNode(xpath).getText();
	}

	/**
	 * 替换节点中内容
	 * @param msg
	 * @param elementName
	 * @param value
	 * @return
	 */
	public static String replaceXmlContent(String msg, String elementName,String value){
		int begin = msg.indexOf("<"+elementName+">");
		int end = msg.indexOf("</"+elementName+">", begin + elementName.length());
		if(begin > -1 && end > -1){
			return msg.replace(msg.substring(begin , end), "<"+elementName+">"+value);
		}
		return msg;
	}

	/**
	 * 支付结果通知查询的返回信息是XML格式的,需要转换成Map
	 *
	 * @param xmlStr
	 * @return
	 * @throws DocumentException
	 */
	public static Map<String, String> switchXml2Map(String xmlStr){
		Map<String, String> responseMap = new HashMap<String, String>();
		try {
			Document doc = DocumentHelper.parseText(xmlStr);
			Element rootE = doc.getRootElement();
			putData(rootE, responseMap);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return responseMap;
	}

	/**
	 *
	 * @param e
	 * @param map
	 */
	private static void putData(Element e, Map<String, String> map) {
		if (e == null) {
			return;
		}
		for (Object element : e.elements()) {
			Element e1 = (Element) element;
			if (!e1.elements().isEmpty()) {
				putData(e1, map);
			} else if (!e1.attributes().isEmpty()) {
				map.put(e1.attribute(0).getValue().trim(), e1.getTextTrim());
			} else {
				map.put(e1.getName().trim(), e1.getTextTrim());
			}
		}
	}

	/**
	 * url请求的参数转MAP
	 *
	 * @param queryString
	 *            请求的参数串
	 * @param enc
	 *            编码
	 * @return
	 */
	public static Map<String, String> Params2Map(String queryString) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		if (queryString != null && queryString.length() > 0) {
			int ampersandIndex, lastAmpersandIndex = 0;
			String subStr, param, value;
			do {
				ampersandIndex = queryString.indexOf('&', lastAmpersandIndex) + 1;
				if (ampersandIndex > 0) {
					subStr = queryString.substring(lastAmpersandIndex,
							ampersandIndex - 1);
					lastAmpersandIndex = ampersandIndex;
				} else {
					subStr = queryString.substring(lastAmpersandIndex);
				}

				int index = subStr.indexOf("=");
				param = subStr.substring(0, index);
				value = subStr.length() == index + 1 ? "" : subStr
						.substring(index + 1);

				paramsMap.put(param, value);

			} while (ampersandIndex > 0);
		} else {
			return null;
		}

		return paramsMap;
	}

	/**
	 * 将Map存储的对象,转换为key=value&key=value的字符
	 *
	 * @param requestParam
	 * @param coder
	 * @return
	 */
	public static String getRequestParamString(Map<String, String> requestParam, String coder) {
		if (null == coder || "".equals(coder)) {
			coder = "UTF-8";
		}
		StringBuffer sf = new StringBuffer("");
		String reqstr = "";
		if (null != requestParam && 0 != requestParam.size()) {
			for (Entry<String, String> en : requestParam.entrySet()) {
				sf.append(en.getKey()
						+ "="
						+ (null == en.getValue() || "".equals(en.getValue()) ? "" :en.getValue()) + "&");
			}
			reqstr = sf.substring(0, sf.length() - 1);
		}
		return reqstr;
	}


	/**
	 * <p>
	 * 获取xml字符串中指定节点的值,对应节点中可能包含&lt;![CDATA[xxxx]]&gt;的(如:&lt;attach&gt;&lt;![
	 * CDATA[支付测试]]&gt;&lt;/attach&gt;)使用此函数<br>
	 * 确定节点不包含&lt;![CDATA[xxxx]]&gt;建议使用 函数parseNodeValueFromXml
	 * </p>
	 *
	 * @param nodeStart
	 *            节点开始标签 eg : &lt;TransactionID&gt;
	 * @param nodeEnd
	 *            节点结束标签 eg : &lt;/TransactionID&gt;
	 * @param src
	 *            原字符串
	 * @return
	 */
	public static String getNodeValueFromXml(String nodeStart, String nodeEnd, String src) {
		String rtnStr = "";
		int nodeStartLength = nodeStart.length();
		int start = src.indexOf(nodeStart);
		int end = src.indexOf(nodeEnd);
		if (start > -1 && end > -1) {
			// 先从xml字符串中截取出对应节点的内容
			rtnStr = src.substring(start + nodeStartLength, end);
		}
		// 判断节点内容是否包含了"CDATA",若有,需要对字符串再次截取以获得数据
		if (StringUtils.isNotBlank(rtnStr) && rtnStr.contains("<![CDATA[")) {
			rtnStr = rtnStr.substring(9, rtnStr.lastIndexOf("]]>"));
		}
		return rtnStr;
	}

	/**
	 * 获取xml字符串中指定节点的值,对应节点中可能包含"<![CDATA[xxxx]]>"的(如:
	 * <attach><![CDATA[支付测试]]></attach>)使用此函数<br>
	 * 确定节点不包含"<![CDATA[xxxx]]>"建议使用 函数parseNodeValueFromXml
	 *
	 * @param nodeName
	 *            节点名字eg: xml
	 * @param xmlStr
	 *            原字符串
	 * @return
	 */
	public static String getNodeValueFromXml(String nodeName, String xmlStr) {
		String nodeStart = "<" + nodeName + ">";
		String nodeEnd = "</" + nodeName + ">";
		return getNodeValueFromXml(nodeStart, nodeEnd, xmlStr);
	}

}

工具四

package com.xxxx.xxxx.common.util;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;



public class XmlUtil {
	
	/**
	 * 将指定的Map对象转换成XML报文
	 * @param map			Map对象
	 * @param root		 	指定XML报文的根节点名称
	 * @param encoding		字符集
	 * @return String		转换后的XML报文
	 * @throws Exception
	 */
	public static String format(Map map, String root, String encoding) throws Exception {
		String xml = null;
		
		if (map != null && map.size() > 0) {
			Document document = DocumentHelper.createDocument();
			document.setXMLEncoding(encoding);
			Element rootElement = document.addElement(root);
			format(rootElement, map);
			xml = document.asXML();
		}
		
		return xml;
	}
	
	/**
	 * 将指定的XML报文转换成Map对象,忽略根节点
	 * @param xml			XML字符串
	 * @return String		转换后的XML报文
	 * @throws Exception
	 */
	public static Map parse(String xml) throws Exception {
		Map map = null;
		
		if (StringUtils.isNotBlank(xml)) {
			SAXReader reader = null;
			StringReader sr = null;
			try {
				reader = new SAXReader();
				sr = new StringReader(xml);
				Document document = reader.read(sr);
				Element root = document.getRootElement();
				map = (Map) parse(root);
				System.out.println(map);
			} finally {
				if (sr != null) {
					sr.close();
				}
			}
		}
		
		
		return map;
	}
	
	/**
	 * 从现有的XML报文中截取指定XML元素相关的内容
	 * @param xmlElmentName	XML元素名称
	 * @return Object		数据对象
	 * @throws Exception
	 */
	public static String getElementXml(String xml, String xmlElmentName) {
		String elementXml = null;
		
		if (StringUtils.isNotBlank(xml)) {
			String perfix = String.format("<%s>", xmlElmentName);
			String suffix = String.format("</%s>", xmlElmentName);
			int beginIndex = xml.indexOf(perfix);
			int endIndex = xml.indexOf(suffix);
			if (beginIndex >= 0 && endIndex >= 0 && endIndex > beginIndex) {
				elementXml = xml.substring(beginIndex, endIndex + suffix.length());
			}
		}
		
		return elementXml;
	}

	/**
	 * 从现有的XML报文中截取指定XML元素的值
	 * @param xml			XML报文
	 * @param xmlElmentName	XML元素名称
	 * @return String		数据对象
	 * @throws Exception
	 */
	public static String getElementValue(String xml, String xmlElmentName) {
		String value = null;
		
		String elementXml = getElementXml(xml, xmlElmentName);
		if (StringUtils.isNotBlank(elementXml)) {
			int beginIndex = elementXml.indexOf(">");
			int endIndex = elementXml.lastIndexOf("<");
			if (beginIndex >= 0 && endIndex >= 0 && endIndex > beginIndex) {
				value = elementXml.substring(beginIndex + 1, endIndex);
			}
		}
		
		return value;
	}

	/**
	 * 从现有的XML报文中截取指定XML元素的值
	 * @param xml			XML报文
	 * @param xmlElmentName	XML元素名称
	 * @param xmlElmentValueXML元素内容
	 * @return Object		数据对象
	 * @throws Exception
	 */
	public static String setElementValue(String xml, String xmlElmentName, String xmlElmentValue) {
		String value = null;
		
		if (StringUtils.isNotBlank(xml)) {
			String perfix = String.format("<%s>", xmlElmentName);
			String suffix = String.format("</%s>", xmlElmentName);
			int beginIndex = xml.indexOf(perfix);
			int endIndex = xml.indexOf(suffix);
			if (beginIndex >= 0 && endIndex >= 0 && endIndex > beginIndex) {
				value = xml.substring(0, beginIndex) + perfix + xmlElmentValue + xml.substring(endIndex);
			}
		}
		
		return value;
	}

	/**
	 * 将指定的数据对象转换成XML元素对象
	 * @param parent		XML元素对象的父节点
	 * @param object		数据对象
	 * @return void			无
	 * @throws Exception
	 */
	private static void format(Element parent, Object object) {
		if (object != null) {
			if (object instanceof Map) {
				Set set = ((Map)object).keySet();
				Iterator iterator = set.iterator();
				while (iterator.hasNext()) {
					Object key = iterator.next();
					Element child = parent.addElement(key.toString());
					Object value = ((Map) object).get(key);
					format(child, value);
				}
			} else if (object instanceof List) {
				Element p = parent.getParent();
				Iterator iterator = ((List)object).iterator();
				while (iterator.hasNext()) {
					Object value = iterator.next();
					Element child = parent.createCopy();
					p.add(child);
					format(child, value);
				}
			} else if (object instanceof Object[]) {
				Element p = parent.getParent();
				for(Object value : (Object[])object) {
					Element child = parent.createCopy();
					p.add(child);
					format(child, value);
				}
				p.remove(parent);
			} else {
				parent.setText(object.toString());
			}
		}
	}
	
	/**
	 * 将XML元素对象转换成数据对象
	 * @param element		XML元素对象
	 * @return Object		数据对象
	 * @throws Exception
	 */
	private static Object parse(Element element) {
		Object object = null;
		
		if (element != null && element.isTextOnly()) {
			object = element.getText();
		} else {
			Map map = new HashMap();
			Iterator iterator = element.elementIterator();
			while (iterator.hasNext()) {
				Element e = (Element) iterator.next();
				String key = e.getName();
				Object value = parse(e);
				Object v = map.get(key);
				if (v != null) {
					List list = null;
					if (v instanceof List) {
						list = (List)v;
					} else {
						list = new ArrayList();
						list.add(v);
						map.put(key, list);
					}
					list.add(value);
				} else {
					map.put(key, value);
				}
			}
			object = map;
		}
		
		return object;
	}
	
}

//
//import java.util.List;
//import java.util.Map;
//
//import org.apache.commons.lang.StringUtils;
//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
//

//public class XmlUtil {
//	private static transient Log log = LogFactory.getLog(XmlUtil.class);
//	/*public static void main(String[] args)throws Exception {
//		List xmList=new ArrayList();
//		List pubList=new ArrayList();
//		List busiList=new ArrayList();
//		
//		ObjBean a=new ObjBean("a", "aaaa");
//		ObjBean b=new ObjBean("b", "bbbb");
//		
//		pubList.add(a);
//		pubList.add(b);
//		
//		ObjBean c=new ObjBean("c", "ccc");
//		ObjBean d=new ObjBean("d", "ddd");
//		busiList.add(c);
//		busiList.add(d);
//		
//		Map pub=new HashMap();
//		pub.put("pub",pubList);
//		pub.put("busi",busiList);
//		List objList=new ArrayList(); 
//		
//		ObjBean pub=new ObjBean("pub",pubList);
//		ObjBean busi=new ObjBean("busi",busiList);
//		
//		objList.add(pub);
//		objList.add(busi);
//	
//		xmList.add(objList);
//		
//		String xml=list2XmlUTF8(xmList,"REQ_PARAM");
//		
//		System.out.println("xml:"+xml);
//	}*/
//	
//	public static String list2XmlUTF8(List list, String rootNode) throws Exception{
//		 String xml = AssembleXml.list2Xml(list, rootNode);
//		 xml = xml.replaceFirst("GBK", "UTF-8");
//		 return xml;  
//	}
//	
//	public static String map2XmlUTF8(Map map, String rootNode) throws Exception{
//		 String xml = AssembleXml.map2Xml(map, rootNode);
//		 xml = xml.replaceFirst("GBK", "UTF-8");
//		 return xml;  
//	}
//	
//	public static String map2XmlGBK(Map map, String rootNode) throws Exception{
//		 String xml = AssembleXml.map2Xml(map, rootNode);
//		 xml = xml.replaceFirst("UTF-8", "GBK");
//		 return xml;  
//	}
//	
//	
//	
//	
//	
//	public static String formatXML(String xml, int ... formatType) throws Exception {  
////        StringWriter out = null;  
////        try{  
////        	Document doc = DocumentHelper.parseText(xml);
////        	
////        	
////        	OutputFormat format = OutputFormat.createCompactFormat();
////        	if(formatType != null && formatType.length > 0){
////        		format = OutputFormat.createPrettyPrint();  
////        	}
////        	
////            format.setEncoding("GBK");
////            out = new StringWriter();  
////            XMLWriter writer = new XMLWriter(out, format);  
////            writer.write(doc);  
//        	
////        } catch (IOException e){  
////           e.printStackTrace();  
////        } finally{  
////        	try {
////        		out.close(); 
////			} catch (Exception e2) {
////				e2.printStackTrace();
////			}
////        }  
////        return out.toString();
//        String ret = null;
//        ret = xml.replaceAll("[\\r\\n\\t]*", "");
//        return ret;
//    }  
//	
//	public static String getValue(String xml, String key1, String key2){
//		String value = "";
//		if(StringUtils.isNotBlank(xml) && StringUtils.isNotBlank(key1) && StringUtils.isNotBlank(key2)){
//			String[] tmp = com.ai.appframe2.util.StringUtils.getParamFromString(xml, key1, key2);
//			if(tmp != null && tmp.length > 0){
//				value = tmp[0];
//			}
//		}
//		return value;
//	}
//	
//	/********************************************组装报文****************************************************/
//	public static String assembleXml(Map map, String trans_id, String plat_code) throws Exception {
//		String xml = AssembleXml.map2Xml(map);
//		
//		//替换签名
//		String regex = getXmlEle(xml, Constant.PublicInfo.VERIFY_CODE);
//		
//		ISafeInterSV safeSV = CmServiceFactory.getSafeInterSV();
//		String signData = trans_id + getXmlEle(xml, Constant.PublicInfo.BUSI_DATA).trim();
//		String replacement = safeSV.sign_SHA1WithRSA("plat_"+plat_code, signData);
//		
//		xml = xml.replaceFirst(regex, createXmlEle(replacement,Constant.PublicInfo.VERIFY_CODE));
//		
//		return xml;
//	}
//
//	public static String createXmlEle(String value, String eleCode) throws Exception {
//		
//		String startEle = Common.LOW + eleCode + Common.GREAT;
//		String endEle = Common.LOW + Common.LINE + eleCode + Common.GREAT;
//		
//		return startEle+value+endEle;
//		
//	}
//	
//	/********************************************组装报文****************************************************/
//	public static String assembleXml1(Map map, String trans_id, String plat_code) throws Exception {
//		String xml = AssembleXml.map2Xml(map);
//		
//		//替换签名
//		String regex = getXmlEle(xml, Constant.PublicInfo.VERIFY_CODE);
//		
//		//ISafeInterSV safeSV = CmServiceFactory.getSafeInterSV();
//		IBsKeyManageSV bsKeyManageSV = (IBsKeyManageSV)ServiceFactory.getSeviceOfLocal(IBsKeyManageSV.class);
//		String signData = trans_id + getXmlEle(xml, Constant.PublicInfo.BUSI_DATA).trim();
//		//String replacement = safeSV.sign_SHA1WithRSA_extSystem("plat_"+plat_code, signData);
//		String replacement = bsKeyManageSV.sign_SHA1WithRSA_extSystem(signData, "plat_"+plat_code);
//		
//		xml = xml.replaceFirst(regex, createXmlEle(replacement,Constant.PublicInfo.VERIFY_CODE));
//		
//		return xml;
//	}
//	
//	
//public static String getXmlEle(String xml, String eleCode) throws Exception {
//		
//		String retXml = null;
//		
//		String startEle = Common.LOW + eleCode + Common.GREAT;
//		String endEle = Common.LOW + Common.LINE + eleCode + Common.GREAT;
//		
//		String emptyEle = Common.LOW + eleCode + Common.LINE + Common.GREAT ;
//		
//		int startIndex = xml.indexOf(startEle);
//		int endIndex = xml.indexOf(endEle);
//		
//		int emptyIndex = xml.indexOf(emptyEle);
//		
//		if(emptyIndex < 0){
//			if(startIndex<0 || endIndex<0 || (startIndex>endIndex)){
//				log.error("截取XML的业务数据部分报文失败:XML报文不合法");
//				throw new Exception("XML报文不合法");
//			}
//			
//			retXml = xml.substring(startIndex, endIndex+endEle.length());
//		}else{
//			retXml = emptyEle;
//		}
//
//		
//		return retXml;
//	}
//}

参考:

https://blog.csdn.net/u014209205/article/details/80480621