Commit 6cbbbb5c by 彭祥礼

支付调整

parent 48fee382
......@@ -289,6 +289,7 @@ public class YxtCardController extends BaseController {
@RequestParam("totalPrice") Double totalPrice,
@RequestParam("openId") String openId){
int totalPrice0 = (int)(totalPrice * 100);
totalPrice0 = 10;
String nonceStr = Sha1Util.getNonceStr();
// 统一下单请求参数
......@@ -300,7 +301,7 @@ public class YxtCardController extends BaseController {
payRequest.setBody("yuan_xian_tong");
payRequest.setOut_trade_no(orderNum);
payRequest.setTotal_fee(Integer.toString(totalPrice0));
payRequest.setSpbill_create_ip("120.24.88.216");
payRequest.setSpbill_create_ip("219.128.144.210");
payRequest.setNotify_url(WxConfig.NOTIFY_URL);
payRequest.setTrade_type("JSAPI");
//payRequest.setOpenid("o22lhwRZP2zbXff7UHH3J8oqH8A0");//临时测试用
......@@ -410,7 +411,7 @@ public class YxtCardController extends BaseController {
orderWrapper.eq("order_num",orderNum);
YxtOrder yxtOrder = new YxtOrder();
yxtOrder.setDelFlag(1);
yxtOrder.setState(1);
yxtOrder.setState(4);
int result = yxtOrderMapper.update(yxtOrder,orderWrapper);
if(result>0){
Wrapper<YxtOrderDetail> detailWrapper = new EntityWrapper<>();
......@@ -433,7 +434,7 @@ public class YxtCardController extends BaseController {
YxtCoupon coupon = new YxtCoupon();
coupon.setState(1);
Wrapper<YxtCoupon> couponWrapper = new EntityWrapper<>();
couponWrapper.eq("state",3);
couponWrapper.eq("state",1);
couponWrapper.in("id",couponIds);
yxtCouponMapper.update(coupon,couponWrapper);
}
......
package com.winsun.controller;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.bean.YxtCoupon;
import com.winsun.bean.YxtOrder;
import com.winsun.bean.YxtOrderDetail;
import com.winsun.bean.YxtSalesLimit;
import com.winsun.mapper.YxtCouponMapper;
import com.winsun.mapper.YxtOrderDetailMapper;
import com.winsun.mapper.YxtOrderMapper;
import com.winsun.mapper.YxtSalesLimitMapper;
import com.winsun.utils.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 院线通销售Controller
* @author 董有沛
* @date 2018年1月22日
*
*/
@Slf4j
@RestController
@RequestMapping("/wxpay")
public class YxtWxPayController extends BaseController {
@Autowired
private YxtOrderMapper yxtOrderMapper;
@Autowired
private YxtCouponMapper yxtCouponMapper;
@Autowired
private YxtSalesLimitMapper yxtSalesLimitMapper;
@Autowired
private YxtOrderDetailMapper yxtOrderDetailMapper;
@Autowired
private RedisTemplate redisTemplate;
public static Lock lock = new ReentrantLock();
// 公众号支付异步回调
@RequestMapping("/payNotify")
@ResponseBody
public void payNotify(HttpServletResponse response, HttpServletRequest request){
// 加入同步锁,防止重复操作导致数据紊乱
lock.lock();
try {
InputStream in = request.getInputStream();
Map<String, String> map = XmlParser.xmlToMap(in);
Map<String, String> respMap = new HashMap<>();
// 通信标识为SUCCESS,则会返回其它参数
if("SUCCESS".equals(map.get("return_code"))){
String sign = map.get("sign");
// 统一下单加密参数
SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
parameters.put("appid", map.get("appid"));
parameters.put("mch_id", map.get("mch_id"));
parameters.put("nonce_str", map.get("nonce_str"));
parameters.put("out_trade_no", map.get("out_trade_no"));
parameters.put("total_fee",map.get("total_fee"));
parameters.put("trade_type", map.get("trade_type"));
parameters.put("openid", map.get("openid"));
parameters.put("is_subscribe", map.get("is_subscribe"));
parameters.put("fee_type", map.get("fee_type"));
parameters.put("transaction_id", map.get("transaction_id"));
parameters.put("result_code", map.get("result_code"));
parameters.put("time_end", map.get("time_end"));
parameters.put("bank_type", map.get("bank_type"));
parameters.put("return_code", map.get("return_code"));
parameters.put("cash_fee", map.get("cash_fee"));
String newSign = WXPayUtil.createSign("UTF-8", parameters);
// 验证支付结果签名
if(null != newSign && sign.equals(newSign)){
String orderNumber = map.get("out_trade_no"); // 获取订单号
Wrapper<YxtOrder> orderWrapper = new EntityWrapper<>();
orderWrapper.eq("order_num",orderNumber);
List<YxtOrder> list = yxtOrderMapper.selectList(orderWrapper);
// 检查该订单号是不是创建
if(list.size()>0){
YxtOrder yxtOrder = list.get(0);
double totalPrice = Double.parseDouble(yxtOrder.getTotalPrice().toString()) * 100;
double totalFee = Double.parseDouble(map.get("total_fee").toString());
if(totalPrice <= totalFee+1){
// 订单状态未修改,则修改
if(!"2".equals(yxtOrder.getState().toString())){
Wrapper<YxtOrder> wrapper = new EntityWrapper<>();
orderWrapper.eq("order_num",orderNumber);
orderWrapper.eq("del_flag",0);
YxtOrder yxtOrder1 = new YxtOrder();
yxtOrder1.setWxOrderNum(map.get("transaction_id"));
yxtOrder1.setState(2);
int num = yxtOrderMapper.update(yxtOrder1,wrapper);
if("电子订单".equals(yxtOrder.getOrderType())){
if(num > 0){
// 更新兑换券状态
Wrapper<YxtOrderDetail> orderDetailWrapper = new EntityWrapper<>();
orderDetailWrapper.eq("order_id",yxtOrder.getId());
List<YxtOrderDetail> orderDetails = yxtOrderDetailMapper.selectList(orderDetailWrapper);
if(!(orderDetails.size()>0)){
log.info("查找销售订单详情无数据!!!");
}
Wrapper<YxtCoupon> couponWrapper = new EntityWrapper<>();
couponWrapper.eq("id",orderDetails.get(0).getYxtId());
List<YxtCoupon> couponList = yxtCouponMapper.selectList(couponWrapper);
if(!(couponList.size()>0)){
log.info("查找销售兑换券无数据!!!");
}
for (YxtCoupon coupon : couponList) {
Wrapper<YxtCoupon> yxtCouponWrapper = new EntityWrapper<>();
yxtCouponWrapper.eq("id",coupon.getId());
yxtCouponWrapper.ne("state",2);
YxtCoupon coupon1 = new YxtCoupon();
coupon1.setState(2);
yxtCouponMapper.update(coupon1,yxtCouponWrapper);
}
this.sendAccount(orderNumber,map.get("openid"));
this.updateSalesLimit(orderNumber,map.get("openid"));
}
}
}
// 将应答结果返回给微信,让微信停止重复通知动作
respMap.put("return_code", "SUCCESS");
respMap.put("return_msg", "OK");
String respStr = XmlParser.map2XmlString(respMap);
log.info(" 支付验证回调 :" + new Date());
response.getWriter().print(respStr);
}else{
log.info("回调接口:付款金额有误");
}
}else{
log.info("回调接口:订单号异常");
}
}else{
log.info("回调接口:支付结果签名验证失败!");
}
}else{
log.info("回调接口:通信标识为FAIL");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void updateSalesLimit(String orderNumber,String openId){
try{
Wrapper<YxtOrder> yxtOrderWrapper = new EntityWrapper<>();
yxtOrderWrapper.eq("order_num",orderNumber);
List<YxtOrder> yxtOrderList = yxtOrderMapper.selectList(yxtOrderWrapper);
Wrapper<YxtSalesLimit> yxtSalesLimitWrapper = new EntityWrapper<>();
yxtSalesLimitWrapper.eq("open_id",openId);
List<YxtSalesLimit> yxtSalesLimitList = yxtSalesLimitMapper.selectList(yxtSalesLimitWrapper);
if(yxtOrderList.size() > 0){
YxtOrder yxtOrder = yxtOrderList.get(0);
int salesNum = yxtOrder.getGoodsNum();
if(yxtSalesLimitList.size() > 0){
YxtSalesLimit yxtSalesLimit = new YxtSalesLimit();
yxtSalesLimit.setSalesNum(salesNum);
Wrapper<YxtSalesLimit> limitEntityWrapper = new EntityWrapper<>();
limitEntityWrapper.eq("open_id",openId);
yxtSalesLimitMapper.update(yxtSalesLimit,limitEntityWrapper);
// String sql = " update yx_yxt_sales_limit set sales_num = sales_num + "+ salesNum +",update_date = now() where open_id = '"+ openId +"' ";
// jdbcTemplate.update(sql);
}else{
YxtSalesLimit yxtSalesLimit = new YxtSalesLimit();
yxtSalesLimit.setSalesNum(salesNum);
yxtSalesLimit.setOpenId(openId);
yxtSalesLimit.setUpdateDate(new Date());
yxtSalesLimitMapper.insert(yxtSalesLimit);
// String sql = " insert into yx_yxt_sales_limit (open_id,sales_num,update_date) values('"+ openId +"',"+ salesNum +",now()) ";
// jdbcTemplate.update(sql);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
public void sendAccount(String orderNumber,String openId){
try{
String accessToken = WxInterfacesUtil.getAccessToken();
String content = "";
List<Map<String,Object>> list = yxtOrderMapper.getCardByNumber(orderNumber);
for(int i=0; i<list.size(); i++){
Map<String, Object> map = list.get(i);
content += "账号:"+ map.get("card_number") +"\n密码: "+ map.get("password") +"\n";
if( (i+1) % 5 == 0 ){
content += "请在15分钟内在院线通兑换,逾期有误,概不负责。";
JSONObject object = new JSONObject();
object.put("content", content);
JSONObject obj = new JSONObject();
obj.put("touser", openId);
obj.put("msgtype", "text");
obj.put("text", object);
String dataStr = obj.toString();
String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken;
String result = HTTPSClient.sendPosts(url, dataStr);
System.out.println(result);
content = "";
}else if(i+1 == list.size()){
content += "请在15分钟内在院线通兑换,逾期有误,概不负责。";
JSONObject object = new JSONObject();
object.put("content", content);
JSONObject obj = new JSONObject();
obj.put("touser", openId);
obj.put("msgtype", "text");
obj.put("text", object);
String dataStr = obj.toString();
String url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken;
String result = HTTPSClient.sendPosts(url, dataStr);
System.out.println(result);
content = "";
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
......@@ -3,8 +3,13 @@ package com.winsun.mapper;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.winsun.bean.YxtOrder;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
/**
* 〈院线通订单Mapper〉
*
......@@ -14,4 +19,7 @@ import org.springframework.stereotype.Component;
@Mapper
@Component
public interface YxtOrderMapper extends BaseMapper<YxtOrder> {
@Select("select cardT.*,date_format(validity_period,'%Y-%m-%d') validity_date from yx_yxt_order orderT,yx_yxt_order_detail detailT,yx_yxt_card cardT where orderT.order_num = #{orderNumber} and orderT.id = detailT.order_id and detailT.yxt_id = cardT.id and orderT.state = 2 ")
List<Map<String,Object>> getCardByNumber(@Param("orderNumber") String orderNumber);
}
......@@ -16,7 +16,7 @@ public class WxConfig {
public static final String headUrl = "http://dianyuanjiangli.com";
public static final String KEY = "WINSUN123456xyjl987654wxpay88888";
public static final String MAC_ID = "1498149672";
public static final String NOTIFY_URL = "http://dianyuanjiangli.com/xyjl/yx/wxpay/yxt!payNotify.action";
public static final String NOTIFY_URL = "http://dianyuanjiangli.com/app/ciop/wxpay/payNotify";
// // 公众号appid 网讯测试服务号
// public static final String APPID = "wxfc18f5186b729d15";
......
package com.winsun.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.*;
@Slf4j
public class XmlParser {
private final String SPCODE_XPATH = "/params/spcode";
private final String PARAMS_XPATH = "/params/*";
Document doc;
public XmlParser() {
}
public XmlParser(String xmlString) throws DocumentException {
loadXml(xmlString);
}
/**
* 设置bean属性值
*
* @param obj
* @param nodes
* @throws Exception
*/
public void setValues(Object obj, List<Node> nodes) throws Exception {
try {
for (Node node : nodes) {
Method[] methods = obj.getClass().getMethods();
for (Method method : methods) {
Class<?>[] paramTypes = method.getParameterTypes();
if (method.getName().toLowerCase(Locale.ENGLISH).equals(
"set" + node.getName())) {
if (StringUtils.isNotEmpty(node.getStringValue().trim())){
if (paramTypes[0].getCanonicalName().endsWith("Long")) {
method.invoke(obj, new Long(node.getStringValue()));
} else if (paramTypes[0].getCanonicalName().endsWith(
"Double")) {
method.invoke(obj,
new Double(node.getStringValue()));
} else {
method.invoke(obj, node.getStringValue());
}
}
}
}
}
} catch (RuntimeException e) {
log.error("设置bean属性值失败。", e);
throw e;
}
}
/**
* 根据xml串和xpath获取spcode
*
* @param xmlString
* @return
* @throws Exception
*/
public String getSpCode(String xmlString) throws Exception {
return getSingleValue(xmlString, SPCODE_XPATH);
}
/**
* 获取单个属性的值
*
* @param xmlString
* @param xpath
* @return
* @throws Exception
*/
public String getSingleValue(String xmlString, String xpath)
throws Exception {
try {
if ((xmlString == null || xmlString.trim().equals(""))
&& doc == null) {
return null;
}
load(xmlString);
Node node = doc.selectSingleNode(xpath);
if (node != null)
return node.getStringValue();
else {
log.info("xml中没有指定的属性信息。" + xpath);
return null;
}
} catch (RuntimeException e) {
log.error("获取指定属性值失败。", e);
throw e;
}
}
/**
* 获取单个属性的值
*
* @param xpath
* @return
*/
public String getSingleValue(String xpath) throws Exception {
return getSingleValue(null, xpath);
}
/**
* 根据输入的xpath,找出所有属性值
*
* @param xmlString
* @param xpath
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public List<String> getMultiValue(String xmlString, String xpath)
throws Exception {
try {
load(xmlString);
List<Node> nodes = doc.selectNodes(xpath);
List<String> results = new ArrayList<String>(0);
if (nodes != null && nodes.size() > 0) {
for (Node node : nodes) {
results.add(node.getStringValue());
}
return results;
} else {
log.info("找不到对应的节点." + xpath);
return null;
}
} catch (DocumentException e) {
log.error("获取属性值失败。", e);
throw e;
}
}
public List<String> getMultiValue(String xpath) throws Exception {
return getMultiValue(null, xpath);
}
/**
* 根据输入的参数名称,从xml串获取参数值
*
* @param xmlString
* @param paramNames 参数名称集
* @return
*/
public List<String> getParams(String xmlString, String[] paramNames)
throws Exception {
reload(xmlString);
return getParams(paramNames, PARAMS_XPATH);
}
public List<String> getParams(String[] paramNames) throws Exception {
return getParams(null, paramNames);
}
/**
* 根据输入的参数名称,从xml串获取值,需要xpath
*
* @param xmlString
* @param paramNames
* @param xpath
* @return
* @throws Exception
*/
public List<String> getParams(String xmlString, String[] paramNames,
String xpath) throws Exception {
try {
List<Node> nodes = getNodes(xmlString, xpath);
List<String> rtnObj = new ArrayList<String>(0);
if(nodes == null) return null;
Outer: for (String name : paramNames) {
for (Node node : nodes) {
if (node.getName().equals(name)) {
rtnObj.add(node.getStringValue());
continue Outer;
}
}
log.info("传入XML参数中未找到 " + name + " 字段");
throw new Exception("传入XML参数中未找到 " + name + " 字段");
}
return rtnObj;
} catch (DocumentException e) {
log.error("从xml串解析参数列表失败。", e);
throw e;
}
}
public List<String> getParams(String[] paramNames, String xpath)
throws Exception {
try {
List<Node> nodes = getNodes(xpath);
List<String> rtnObj = new ArrayList<String>(0);
if(nodes == null) return null;
Outer: for (String name : paramNames) {
for (Node node : nodes) {
if (node.getName().equals(name)) {
rtnObj.add(node.getStringValue());
continue Outer;
}
}
log.info("传入XML参数中未找到 " + name + " 字段");
//throw new Exception("传入XML参数中未找到 " + name + " 字段");
}
return rtnObj;
} catch (DocumentException e) {
log.error("从xml串解析参数列表失败。", e);
throw e;
}
}
/**
* 过滤xmlString,根据输入的xml和节点名字以及值过滤条件过滤掉不需要的节点。
* (注意,被删除掉的是输入的节点的父节点,会有非根结点的验证。)
*
* @param xmlString
* 需要过滤的串
* @param xpath
* 查找的xpath串(包含查找的条件信息)
* @return 过滤后的xml串
*/
@SuppressWarnings("unchecked")
public String filterOutput(String xmlString, String xpath) throws Exception {
try {
load(xmlString);
if (doc == null)
return null;
List<Node> nodes = doc.selectNodes(xpath);
for (Node node : nodes) {
node.getParent().remove(node);
}
return doc.asXML();
} catch (DocumentException e) {
log.error("过滤xml串失败。", e);
throw e;
}
}
public void appendData(String xpath, String... xmlStrings) {
}
/**
* 根据指定的xpath获取节点集合。
*
* @param xpath
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public List<Element> getELements(String xmlString, String xpath)
throws Exception {
try {
load(xmlString);
if (doc == null)
return null;
List<Element> nodes = doc.selectNodes(xpath);
return nodes;
} catch (DocumentException e) {
log.error("获取节点集合失败。", e);
throw e;
}
}
public List<Element> getELements(String xpath) throws Exception {
return getELements(null, xpath);
}
@SuppressWarnings("unchecked")
public List<Node> getNodes(String xmlString, String xpath) throws Exception {
try {
load(xmlString);
if (doc == null)
return new ArrayList<Node>(0);
List<Node> nodes = doc.selectNodes(xpath);
return nodes;
} catch (DocumentException e) {
log.error("获取节点失败。", e);
throw e;
}
}
public List<Node> getNodes(String xpath) throws Exception {
if(doc == null) return null;
return doc.selectNodes(xpath);
}
public Node getSingleNode(String xmlString, String xpath) throws Exception {
try {
load(xmlString);
if (doc == null)
return null;
Node node = doc.selectSingleNode(xpath);
return node;
} catch (RuntimeException e) {
log.error("获取节点失败。", e);
throw e;
}
}
public Node getSingleNode(String xpath) throws Exception {
return getSingleNode(null, xpath);
}
@SuppressWarnings("unchecked")
public String addNodes(String xmlString, String xpath, String nodeName,
String value) {
try {
load(xmlString);
if (doc == null)
return null;
List<Node> nodes = doc.selectNodes(xpath);
for (Node node : nodes) {
Element e = (Element) node;
Element c = e.addElement(nodeName);
c.addText(value);
}
return doc.asXML();
} catch (Exception e) {
log.error("添加节点失败。", e);
return null;
}
}
public String addNodes(String xpath, String nodeName, String value) {
return addNodes(null, xpath, nodeName, value);
}
private boolean validateNull(Object s) {
if (s == null || s.toString().trim().equals("")) {
return false;
}
return true;
}
public String getAttributeValue(String xmlString, String xpath)
throws DocumentException {
try {
load(xmlString);
if (doc == null)
return null;
Attribute a = (Attribute) doc.selectObject(xpath);
return a.getValue();
} catch (DocumentException e) {
log.error("获取属性值失败。", e);
throw e;
} catch (RuntimeException e) {
log.error("获取属性值失败。", e);
throw e;
}
}
public String getAttributeValue(String xpath) throws DocumentException {
return getAttributeValue(null, xpath);
}
public String getXmlString() {
if (doc != null)
return doc.asXML();
else
return null;
}
private void loadXml(String xml) throws DocumentException {
try {
if (xml == null || xml.equals("")) {
return;
}
doc = DocumentHelper.parseText(xml);
} catch (DocumentException e) {
log.error("创建xml解析器失败。", e);
throw e;
}
}
private void load(String xml) throws DocumentException {
if (doc == null && xml != null && !xml.trim().equals("")) {
loadXml(xml);
}
}
/**
* 强行重新读入xml
*
* @param xmlString
* @throws DocumentException
*/
public void reload(String xmlString) throws DocumentException {
loadXml(xmlString);
}
public static void main(String[] args) throws Exception {
String xml = "<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:a=\"http://www.w3.org/2005/08/addressing\"><s:Header><a:Action s:mustUnderstand=\"1\">http://tempuri.org/ISarftService/ProcessResponse</a:Action><ActivityId CorrelationId=\"ef4f07d1-fa4a-48ec-9cb3-73d1b02edcff\" xmlns=\"http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics\">47cd77f2-ed60-4084-9d4c-87bf3c78bc1d</ActivityId></s:Header><s:Body xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><reply xmlns=\"http://www.crifst.ac.cn/2013/OTSAPI\"><msg>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;&lt;OnlineTicketingServiceReply xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" Datetime=\"2014-12-02T15:38:30\" Version=\"1.0\"&gt;&lt;QuerySessionReply ErrorCode=\"\" ErrorMessage=\"\" Id=\"ID_QuerySessionReply\" Status=\"Success\"&gt;&lt;Sessions CinemaCode=\"0042\"&gt;&lt;/Sessions&gt;&lt;/QuerySessionReply&gt;&lt;/OnlineTicketingServiceReply&gt;</msg></reply></s:Body></s:Envelope>";
XmlParser parser = new XmlParser();
parser.reload(xml);
Document resultDoc = null;
try {
resultDoc = DocumentHelper.parseText(xml);
} catch (DocumentException e) {
e.printStackTrace();
}
Element rootEle = resultDoc.getRootElement();
Element ele = rootEle.element("s:Body");
System.out.print("end");
}
/**
* 根据request将XML流解析成MAP
*
* @return
* @throws IOException
* @throws DocumentException
*/
public static Map<String, String> xmlToMap(InputStream in) throws DocumentException, IOException {
Map<String, String> map = new HashMap<>();
SAXReader reader = new SAXReader();
Document document = reader.read(in);
Element root = document.getRootElement();
List<Element> list = root.elements();
for (Element e : list) {
map.put(e.getName(), e.getText());
}
in.close();
return map;
}
/**
* map转xml map中没有根节点的键
* @param map
* @param rootName
* @throws DocumentException
* @throws IOException
*//*
public static Document map2xml(Map<String, Object> map, String rootName) throws DocumentException, IOException {
Document doc = DocumentHelper.createDocument();
Element root = DocumentHelper.createElement(rootName);
doc.add(root);
map2xml(map, root);
//System.out.println(doc.asXML());
//System.out.println(formatXml(doc));
return doc;
}
*//**
* map转xml map中含有根节点的键
* @param map
* @throws DocumentException
* @throws IOException
*//*
public static Document map2xml(Map<String, Object> map) throws DocumentException, IOException {
Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();
if(entries.hasNext()){ //获取第一个键创建根节点
Map.Entry<String, Object> entry = entries.next();
Document doc = DocumentHelper.createDocument();
Element root = DocumentHelper.createElement(entry.getKey());
doc.add(root);
map2xml((Map)entry.getValue(), root);
//System.out.println(doc.asXML());
//System.out.println(formatXml(doc));
return doc;
}
return null;
}
*//**
* map转xml
* @param map
* @return
*//*
private static Element map2xml(Map<String, Object> map, Element body) {
Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, Object> entry = entries.next();
String key = entry.getKey();
Object value = entry.getValue();
if(key.startsWith("@")){ //属性
body.addAttribute(key.substring(1, key.length()), value.toString());
} else if(key.equals("#text")){ //有属性时的文本
body.setText(value.toString());
} else {
if(value instanceof java.util.List ){
List list = (List)value;
Object obj;
for(int i=0; i<list.size(); i++){
obj = list.get(i);
//list里是map或String,不会存在list里直接是list的,
if(obj instanceof java.util.Map){
Element subElement = body.addElement(key);
map2xml((Map)list.get(i), subElement);
} else {
body.addElement(key).setText((String)list.get(i));
}
}
} else if(value instanceof java.util.Map ){
Element subElement = body.addElement(key);
map2xml((Map)value, subElement);
} else {
body.addElement(key).setText(value.toString());
}
}
//System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
return body;
} */
public static String map2XmlString(Map<String, String> map) {
String xmlResult = "";
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
for (String key : map.keySet()) {
String value = "<![CDATA[" + map.get(key) + "]]>";
sb.append("<" + key + ">" + value + "</" + key + ">");
}
sb.append("</xml>");
xmlResult = sb.toString();
return xmlResult;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment