Java实现接收xml格式数据并解析,返回xml格式数据

需求描述:后端接受xml格式数据,解析出相应数据,并返回xml格式数据。

xml 复制代码
		<!--XML解析-->
		<dependency>
			<groupId>com.fasterxml.jackson.dataformat</groupId>
			<artifactId>jackson-dataformat-xml</artifactId>
		</dependency>
		<dependency>
			<groupId>com.thoughtworks.xstream</groupId>
			<artifactId>xstream</artifactId>
			<version>1.4.9</version>
		</dependency>
java 复制代码
package com.zlp.cps.dto;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.Data;

/**
 * 接收xml格式数据解析类
 * 
 * @author zlp
 * @date 2023/8/25
 **/
@Data
@XStreamAlias("xml")
public class WxUserMessageModel {

    @XStreamAlias("ToUserName")
    private String toUserName;
    @XStreamAlias("FromUserName")
    private String fromUserName;

    @XStreamAlias("CreateTime")
    private Long createTime;

    @XStreamAlias("MsgType")
    private String msgType;

    @XStreamAlias("Content")
    private String content;

    @XStreamAlias("MsgId")
    private String msgId;

    @XStreamAlias("Title")
    private String title;

    @XStreamAlias("Description")
    private String description;

    @XStreamAlias("Url")
    private String url;

    /**
     * 订阅或者取消订阅的事件
     */
    @XStreamAlias("Event")
    private String event;

    @XStreamAlias("EventKey")
    private String eventkey;
}
java 复制代码
    public String acceptMsg(HttpServletRequest request, ServletResponse response) {
        // 数据提取
        StringBuffer reqXmlData = new StringBuffer();
        try {
            InputStream inputStream = request.getInputStream();
            String s;
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            while ((s = in.readLine()) != null) {
                reqXmlData.append(s);
            }
            in.close();
            inputStream.close();
        } catch (IOException e) {
            System.out.println("流解析xml数据异常!");
            e.printStackTrace();
        }
        //判断请求数据是否为空
        if (reqXmlData.length() <= 0) {
            System.out.println("请求数据为空!");
        }
        //json类型数据
        JSONObject jsonObject = XML.toJSONObject(reqXmlData.toString());
        log.info("xml :{}", jsonObject.toString());
        Object obj = jsonObject.get("xml");
        JSONObject data = JSONUtil.parseObj(obj);
        String fromUserName = data.get("FromUserName").toString();
        String toUser = data.get("ToUserName").toString();
        String context = data.get("Content").toString();

        // 返回数据
        WxUserMessageModel responseXmlData = new WxUserMessageModel();
        responseXmlData.setToUserName(fromUserName);
        responseXmlData.setFromUserName(toUser);
        responseXmlData.setCreateTime(System.currentTimeMillis());
        responseXmlData.setMsgType("text");
        // 按需编写业务
        if (context.startsWith(GzhConstant.tbSearch)) {
            String[] split = context.split("\\+");
            context = split[1];
            long pageNum = 1L;
            if (split.length > 2) {
                pageNum = Long.parseLong(split[2]);
            }
            // 调用淘宝商品搜索服务
            TbCpsReq req = new TbCpsReq();
            req.setKeyword(context);
            req.setPageNum(pageNum);
            req.setPageSize(8L);
            BaseResponse search = tbCpsService.search(req);
            List<TbMaterialData> list = (List<TbMaterialData>) search.getData();
            if (ListUtil.isEmpty(list)) {
                context = "该商品暂时没有优惠券";
            } else {
                context = convertSearchToMsg(list);
            }
        } else if (context.startsWith(GzhConstant.pddSearch)) {
            context = "拼多多搜索服务升级中!!!";
        } else if (context.startsWith(GzhConstant.jdSearch)) {
            context = "京东搜索服务升级中!!!";
        } else {
            return GzhConstant.defaultReply;
        }

        responseXmlData.setContent(context);

        XStream xstream = new XStream();
        xstream.processAnnotations(WxUserMessageModel.class);
        xstream.setClassLoader(WxUserMessageModel.class.getClassLoader());
        log.info("return xml : {}", xstream.toXML(responseXmlData));
        return xstream.toXML(responseXmlData);  //XStream的方法,直接将对象转换成 xml数据
    }
相关推荐
h***06654 小时前
【JSqlParser】Java使用JSqlParser解析SQL语句总结
java·开发语言·sql
代码or搬砖4 小时前
Java Lambda 表达式全面详解
java·开发语言·python
okseekw4 小时前
Java初学者的static探险记:原来“静态”是这么个省心玩意儿!
java
这周也會开心4 小时前
JDK1.8新增语法
java·开发语言
心随雨下4 小时前
TypeScript泛型开发常见错误解析
java·开发语言·typescript
DonaldCen6664 小时前
Java 王者修炼手册【Mysql篇 - SQL执行存储流程】:拆解 InnoDB 存储结构与 SQL 执行流程,吃透 Buffer Pool 和 Change
java
旺仔Sec4 小时前
2025年广东省职业院校技能大赛高职组“区块链技术应用”竞赛试题(二)
java·区块链
Boop_wu5 小时前
[Java EE] 多线程编程进阶
java·数据库·java-ee
w***37515 小时前
SpringBoot【实用篇】- 测试
java·spring boot·后端
q***61415 小时前
Java实战:Spring Boot实现WebSocket实时通信
java·spring boot·websocket